/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
| Ruby | Message |
|---|---|
| 3.4+ | undefined method 'name' for nil (NoMethodError) |
| 3.3 | undefined method `name' for nil (NoMethodError) |
| 3.2 and earlier | undefined 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
users = { 1 => { name: "Ada" } }
user = users[2] # missing key: nil
puts user[:name].upcase # undefined method '[]' for nilThe method in the message is the one called on nil: here [], because user[:name] calls user.[](:name).
Fixes
# 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 userSources
Related pages
commands · bundlerbundle exec: run a command with the Gemfile's gem versionsbundle exec CMD runs a command with exactly the gem versions in Gemfile.lock, avoiding conflicts with other installed versions. When you need it, and binstubs.errors · phpPHP Fatal error: Uncaught Error: Call to undefined functionPHP throws Call to undefined function when a function is not defined or its extension (mbstring, curl, mysqli) is not loaded. Check php -m and includes.errors · javascriptTypeError: x is not a function (JavaScript)JavaScript throws x is not a function when you call a value that is undefined, an object or a string: a typo, a missing import, or .map on a non-array. Fixes.commands · rubyruby convert string to integer: to_i vs Integer()Convert a string to an integer in Ruby: to_i never fails and returns 0 for bad input, Integer() raises ArgumentError, exception: false returns nil. Bases too.