Skip to content

Ruby error: undefined method for nil:NilClass

Sean Lerner edited this page Apr 5, 2017 · 2 revisions

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.

How To Fix

Step 1: Check return value of method you're is what you expect

Check to see what the return value of the method you're calling is. Is the return value the object you expect? You may need to handle a situation where you receive an false or nil value back.

For example, here we're searching for a contact by an id number that does not exist:

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_name

The 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.find(99)
if contact
  puts contact.full_name
else
  puts 'Contact not found'
end

Step 2: Define instance variables before using them

Unlike local variables, which when undefined, raise an undefined local variable error, instance variables start out as a NilClass, and you won't receive a helpful undefined variable style message. Instead, you'll only learn about the issue when you try to call a method on them.

For example, here 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 age

Our 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. Ruby was expecting that NilClass had a method called - (the subtraction symbol). In other words, the ruby interpreter expected this:

 class NilClass
   def -(value)
    2017 - value
  end
end

@year_born = 1973
age = @current_year - @year_born
puts age

Of course, we wouldn't add a method like this 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 age
Clone this wiki locally