-
Notifications
You must be signed in to change notification settings - Fork 2
Ruby error: undefined method for nil:NilClass
If your error looks like ...
undefined method `my_method_name' for nil:NilClass (NoMethodError)... this means that you're calling a method on an object that has not been defined properly.
Here we're searching for a contact by an id number that does not exist:
# my_program
class Contact
def self.find(id)
# code that finds a contact by id
# returns nil if contact is not found
end
end
contact = Contact(99)
puts contact.full_nameThe error:
/path/to/my_program.rb:65:in `<top (required)>':
undefined method `full_name' for nil:NilClass (NoMethodError)We expected contact to be defined, but as the contact wasn't found, we couldn't call the method full_name on it.
To fix this error, we could adjust our program like so:
contact = Contact(99)
if contact
puts contact.full_name
else
puts 'Contact not found'
endHere we're trying to determine someones age by the current year and the year they were born:
# age.rb
@year_born = 1973
age = @current_year - @year_born
puts ageOur error:
age.rb:2:in `<main>': undefined method `-' for nil:NilClass (NoMethodError)@current_year was never defined, and as @current_year begins with an @, it is treated as an instance variable. Undefined instance variables are set to a NilClass instance. Ruby was expecting that NilClass had a method called - (the subtraction symbol). In other words, the ruby interpreted expected this:
class NilClass
def -(value)
2017 - value
end
end
@year_born = 1973
age = @current_year - @year_born
puts ageOf course, we wouldn't add this method to NilClass in this way.
What we need to do is define @current_year first:
@current_year = 2017
@year_born = 1973
age = @current_year - @year_born
puts ageThis is a living document. If you have anything to add, change or remove, please let us know. Or better yet, as it's a wiki, make the change yourself!