Skip to content
undefined method '...' for ...

undefined method '...' for ...

DodaTech 3 min read

Ruby’s undefined method '...' for ... (a NoMethodError) fires when you call a method that doesn’t exist on the receiver — it doesn’t respond to that message.

What It Means

Ruby is a message-passing language: when you call object.method_name, Ruby sends the method name as a message to the object. If the object’s class (or its ancestors) doesn’t define that method, Ruby raises NoMethodError. The error message tells you both the method name and the object’s class, which is your primary debugging clue.

Why It Happens

  • A typo in the method name (to_s vs to_s vs to_string).
  • The object is nil — calling .length on nil gives undefined method 'length' for nil:NilClass.
  • The method exists but belongs to a different class (calling an Array method on a String).
  • You forgot to include a module that defines the method.
  • The method is defined later in the file but you’re calling it before the definition.
  • The object is of a different type than you expected (e.g., a Hash instead of an Array).

How to Fix It

Step 1: Check if the object is nil

This is the most common cause:

# Bad — user might be nil
user.name

# Debug with:
puts user.inspect  # => nil
user&.name         # Safe navigation operator — returns nil instead of raising

Step 2: Verify the method name spelling

# Typo — missing 'i'
"hello".lenght

# Correct
"hello".length

Step 3: Check what class the object actually is

puts object.class
puts object.methods.sort  # List all available methods

Step 4: Include the missing module

If the method comes from a module you forgot to include:

module Greetable
  def greet
    "Hello!"
  end
end

class Person
  include Greetable  # Without this, greet() won't be available
end

Person.new.greet  # => "Hello!"

Step 5: Check for private methods

If the method exists but is private:

class MyClass
  private
  def secret_method
    "secret"
  end
end

obj = MyClass.new
obj.secret_method  # NoMethodError (private method)

# Use send to bypass access control (for debugging only)
obj.send(:secret_method)

Step 6: Use respond_to? to guard calls

if object.respond_to?(:name)
  object.name
else
  "Method not available"
end
What does 'undefined method for nil:NilClass' mean?
It means you called a method on nil — a variable that has no value. For example, user.address.city fails if user.address is nil, because nil doesn’t have a city method. Use the safe navigation operator &. (e.g., user&.address&.city) to chain calls safely.
How do I list all methods available on an object?
Call .methods on the object: object.methods.sort. To see only the methods unique to its class (not inherited), use object.methods - object.class.superclass.instance_methods. Use .private_methods and .protected_methods to see restricted methods.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro