DEV Community

loading...

Discussion on: NoMethodError: undefined method for nil:NilClass... Explained

Collapse
marckohlbrugge profile image
Marc Köhlbrugge • Edited

This one tripped up me all the time when I was just starting out. While the error seems to be about the method, it's usually the object you're trying to call it on that is problematic somehow.

If the object is allowed to be nil, you want to check its presence before calling any method on it. For example:

coffee.drink_it if coffee.present? 

Or if you like concise code:

coffee&.drink_it 
# shorthand for `coffee && coffee.drink_it`
# which basically does the same thing as the present? check

Small nitpick about the example code in article: if my_hash was an actual hash, the error would say {:foo => :bar}:Hash instead of nil:NilClass.