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.
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 nil
respond with nil
to methods it doesn't know.
To be consistent, you should define respond_to_missing?
:
class NilObj
def method_missing(*_)
nil
end
def respond_to_missing?(*_)
true
end
end
If you did monkey patch method_missing
like you are suggesting, especially if you also redefine respond_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 nil
would respond to to_ary
would 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 rescue NoMethodError
, so even without the respond_to_missing?
you could get some strange side effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With