Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I monkey patch NilClass to return nil for missing methods?

Tags:

null

ruby

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

  1. What am I doing wrong, what's the correct way to deal with having the possibility of a nil object

  2. 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
like image 519
user160917 Avatar asked Mar 17 '12 03:03

user160917


1 Answers

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.

like image 61
Marc-André Lafortune Avatar answered Sep 21 '22 16:09

Marc-André Lafortune