2015-02-17
Say you’re in Rails and want check that a method exists & that it is not nil:
One way you could do this is:
If you were cleverer, you could just do:
The trouble with these approaches is they can become cumbersome:
if my_object &&
my_object.my_method &&
my_object.my_method.my_second_method
my_object.my_method.my_second_method
And that’s using the more concise syntax… A better approach would be to use the Object#try method. It ‘tries’ an object’s method and, instead of going mental, calmly returns nil if that method doesn’t work.
Ta da! This makes the more nested existence-validations read much better:
If you’re using standard ruby, the #defined?
and #nil?
methods could help…