codahale.com٭blog

This is my old blog. My current writing is here: codahale.com

NilClass, Devourer Of Errors

Update: This behavior was removed from ruby2ruby 1.1.8 — upgrade and make sure your code works.

From #sequel

[4:03pm] apeiros: ciconia, does sequel add a method_missing that swallows all to NilClass?
[4:05pm] codahale: I think it does.
[4:05pm] codahale: Yeah, it does.
[4:07pm] codahale: I'd seen that behavior in some of my specs -- wasn't sure where it was coming from.
[4:15pm] codahale: Actually, that's in ruby2ruby.
[4:16pm] codahale: Yeah, line #8 in ruby2ruby.rb.
[4:18pm] codahale: apeiros: Is the NilClass#method_missing a real problem for you, or just an unexpected quirk?
[4:19pm] apeiros: it's a real problem
[4:19pm] apeiros: it's a bugkiller
[4:19pm] apeiros: or better said: a debugging/bugfinding killer
[4:20pm] apeiros: an unexpected nil is carried on far far longer than it should and normally would. makes debugging PITA.

Lines 8-12 of ruby2ruby.rb

class NilClass # Objective-C trick
  def method_missing(msg, *args, &block)
    nil
  end
end

An experiment:

>> nil.why_god_why
NoMethodError: undefined method `why_god_why' for nil:NilClass
	from (irb):1
>> require 'ruby2ruby'
=> true
>> nil.why_god_why
=> nil
>> @no_se_existe.please_to_be_raising_error_now
=> nil

Just so’s you know.

3 Responses to “NilClass, Devourer Of Errors”

  1. Matthijs Langenberg Says:

    Whoah, that leads to some odd behaviour. What’s the good side of the trick actually?

  2. Coda Says:

    Matthijs — I don’t know that there is a good side, besides making it super-extra-interesting to track down bugs involving nils and therefore improving your debugging skills. ;-)

  3. Sunny Says:

    I have to agree that this is really crappy behavior. I spent about half an hour trying to figure out why my object wasn’t throwing any errors before finally figuring out that the value was nil. Of course, would have been easy to catch except that I’m expecting nil to throw errors on missing methods. Ugh…