Skip to content

/errors/ruby/undefined-method-for-nil

Ruby NoMethodError: undefined method for nil

The commands on this page have not been executed by our verification runner yet.updated
tool
Ruby
exit code
1
versions
Ruby 3.4 (current wording), Ruby 3.3 and earlier (older wording)
os
any

NoMethodError: undefined method 'name' for nil means Ruby called the method name on an object that was nil. The method exists on the object you expected, but the variable held nil, usually because a lookup found nothing. Find where the value came from (the backtrace points at the line), then handle the missing case with fetch, a guard, or the safe navigation operator &..

Message formats by Ruby version

RubyMessage
3.4+undefined method 'name' for nil (NoMethodError)
3.3undefined method `name' for nil (NoMethodError)
3.2 and earlierundefined method `name' for nil:NilClass (NoMethodError)

Ruby 3.4 changed the opening backtick to a single quote in error messages. Searching for undefined method plus for nil matches every version.

Example

app.rb
users = { 1 => { name: "Ada" } }
user = users[2]          # missing key: nil
puts user[:name].upcase  # undefined method '[]' for nil

The method in the message is the one called on nil: here [], because user[:name] calls user.[](:name).

Fixes

ruby
# 1. Fail loudly with a useful error when the key must exist
user = users.fetch(2)                    # KeyError: key not found: 2

# 2. Default value
user = users.fetch(2, { name: "guest" })

# 3. nil is acceptable: safe navigation returns nil instead of raising
puts user&.dig(:name)&.upcase

# 4. Guard clause
return unless user

Sources