In other languages like (objective-c for example) calling a method on a nil object fails silently and returns nil but in ruby you get errors like this…
undefined method `some_method' for nil:NilClass
which (for me) results in code like this:
if some_object && some_object.cool? # instead of if some_object.cool?
# do some cool stuff
end
or
some_object.do_awsome_thing if some_object
Which all seems backwards and weird.
Two questions
-
What am I doing wrong, what’s the correct way to deal with having the possibility of a nil object
-
What kinds of awful awful things would happen if I just monkey patched the nil object to return nil for missing_methods?
IE:
class NilClass
def missing_method
nil
end
end
It’s a design choice, and I imagine it would have been possible to have
nilrespond withnilto methods it doesn’t know.To be consistent, you should define
respond_to_missing?:If you did monkey patch
method_missinglike you are suggesting, especially if you also redefinerespond_to_missing?accordingly, you might get some strange side effects as duck typing requires some introspection and that is typically done by checking if an object respond to something than a particular class.For instance, the fact that
nilwould respond toto_arywould seem to suggest that it is “array-like”, when it is not the case.Some builtin methods will call
respond_to?, and a few will simply call and rescueNoMethodError, so even without therespond_to_missing?you could get some strange side effects.