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
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
But loveliness
does not exist for a string, so when I type it, I will get...
NoMethodError: undefined method loveliness for nil:NilClass
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
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
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)
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:
Or if you like concise code:
Small nitpick about the example code in article: if
my_hash
was an actual hash, the error would say{:foo => :bar}:Hash
instead ofnil:NilClass
.Haha. Very basic but pesky one for beginners.
I can say nearly one third of SO questions are javascript version of this problem.
Undefined is not a function
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
I'm actually being shown this error when I try to save an article here in dev.to ... ironic