NoMethodError
RubyFATALCommonMethod
Undefined method called on object
Quick Answer
Check the object type with .class and use respond_to? or the safe navigation operator &. to guard against nil.
What this means
Raised when a method is called on an object that does not respond to it. This is one of the most common Ruby errors, frequently caused by calling a method on nil or a type mismatch.
Why it happens
- 1Calling a method on nil when a variable was expected to hold an object
- 2Typo in method name
- 3Method defined in a module that was not included
- 4Calling a private method from outside the class
Fix 1
Safe navigation operator
Safe navigation operator
user = find_user(id) # may return nil name = user&.name # returns nil safely instead of raising
Why this works
The &. operator short-circuits and returns nil if the receiver is nil, preventing NoMethodError.
Fix 2
Guard with respond_to?
Guard with respond_to?
if obj.respond_to?(:process)
obj.process
else
raise TypeError, "Expected a processable object, got #{obj.class}"
endWhy this works
respond_to? checks at runtime whether the method exists before calling it.
Code examples
Reproducing the errorruby
nil.upcase # NoMethodError: undefined method 'upcase' for nil
Safe navigation operatorruby
user = nil puts user&.name # => nil, no error raised
Rescue NoMethodErrorruby
begin
result = obj.missing_method
rescue NoMethodError => e
puts "Error: #{e.message}"
endSame error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev