DEV Community

Cover image for NoMethodError: undefined method for nil:NilClass... Explained
Ben Halpern
Ben Halpern Subscriber

Posted on

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

This is a common Ruby error which indicates that the method or attribute for an object you are trying to call on an object has not been defined.

NoMethodError: undefined method SOME_METHOD for nil:NilClass
Enter fullscreen mode Exit fullscreen mode

For example, the String class in Ruby has the method size (which is synonymous with length, so I can write...

greeting = "hello"
greeting.size
#=> 5
Enter fullscreen mode Exit fullscreen mode

But loveliness does not exist for a string, so when I type it, I will get...

NoMethodError: undefined method loveliness for nil:NilClass
Enter fullscreen mode Exit fullscreen mode

I find this will come up when I think I'm operating on an object with methods, but I'm actually operating on a hash with attributes.

my_hash[:loveliness]
# "very lovely" yay, this is a thing that exists!
my_hash.loveliness
# NoMethodError: undefined method loveliness nil:NilClass
Enter fullscreen mode Exit fullscreen mode

Of course, because this is Ruby, we can actually define loveliness if we wanted to very easily by monkeypatching the String class.

class String

  def loveliness
    "very lovely"
  end

end
Enter fullscreen mode Exit fullscreen mode

Now we know how lovely our string is. If I was mistaken or unclear, please feel free to add a comment to clarify anything here.

Happy coding ❤️

Top comments (5)

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? 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
bravemaster619 profile image
bravemaster619 • Edited

Haha. Very basic but pesky one for beginners.
I can say nearly one third of SO questions are javascript version of this problem.

Collapse
 
itsjzt profile image
Saurabh Sharma

Undefined is not a function

Collapse
 
worc profile image
worc

yikes... what a mess, the more i work with ruby and search for these kinds of issues, the less thrilled i am with the design of the language

Collapse
 
samfieldscc profile image
Sam Fields

I'm actually being shown this error when I try to save an article here in dev.to ... ironic