What does undefined method for nil:NilClass mean, and how do I fix it?
This error means you called a method on nil, Ruby's value for nothing, and nil does not have that method. The bug is almost never the method name. It is the earlier line where a value you expected did not arrive. Find which variable is nil, find why, then fix the source or guard the call.
Cite
Poignant Guide Ruby Q&A, "What does undefined method for nil:NilClass mean, and how do I fix it?", https://poignantguide.net/answers/read/what-does-undefined-method-for-nilnilclass-mean-and-how-do-i-fix-it/, accessed 2026-11-17.- Fenwick HaleStaffStaff: gems, Rails, tooling and debugging ·
What the message says
A NoMethodError is Ruby's report that you sent a message (called a method) to an object that has no such method. The NoMethodError documentation describes it as raised when a method is called on a receiver which does not have it defined. The receiver is the object on the left of the dot. Here is the classic case:
user = { name: "Ada" } puts user[:email].upcase # => undefined method `upcase' for nil (NoMethodError)user[:email]finds no key called:email, so it returnsnil. Thennil.upcasefails. The wording depends on your Ruby. Older versions, and some pages of the Ruby docs, printfor nil:NilClass. The Ruby 3.3 release notes say NoMethodError messages stopped using the object'sinspecttext and now name the class instead, so you will see the shorterfor nilin Ruby 3.3. Both mean the same thing: the receiver was nil.The NilClass documentation calls it the class of the singleton object
nil, which means there is only one nil and it has only a short list of methods, such asnil?,to_sandto_a. That is whyupcase,length,eachand+on nil all fail.Where nil comes from
- A missing hash key or array position.
{}[:x]and[1, 2][5]both return nil. - A method that returns nil.
putsreturns nil, soname = puts("hi")leaves name empty. - A variable that was never set. An instance variable like
@nameis nil until you assign it. This is common inside a class whereinitializenever set it. - A search that found nothing. The Ruby docs show
"Python is fascinating!".match(/(ruby) is (\w+)/i), which returns nil because there is no match, and then.values_atfails. - A method whose last line is not the value you meant. Ruby returns the last expression, and if that line is a
putsor anifthat did not run, the method hands back nil.
Find the nil, then choose a fix
Print the suspect with
p, sincepshowsnilas the word nil, whereputsshows a blank line:email = user[:email] p email # => nilNow pick the fix that matches your intent:
Fix Example Use when Fix the source Add email:when you build the hashThe value should always exist Default with ||(user[:email] || "").upcaseA missing value has a sensible stand-in Hash#fetch user.fetch(:email, "none")You want a default or a loud error for a missing key Safe navigation &.user[:email]&.upcaseMissing is fine, and nil is an acceptable result Explicit check puts "No email" if email.nil?You need different behavior for missing The calling methods documentation explains the safe navigation operator
&.: it skips the call when the receiver is nil and returns nil, without evaluating the arguments. It also warns that&.skips only the next call, so a longer chain needs it at each step:m = "Python is fascinating!".match(/(ruby) is (\w+)/i) p m&.values_at(1, 2) # => nil p m&.values_at(1, 2)&.join(" ") # => nilA word of caution:
&.hides the problem as well as the error. If a value should never be missing, a loud failure is more useful, so preferfetchwithout a default, which raises aKeyErrorthat names the missing key.user.fetch(:email) # => key not found: :email (KeyError)Mistakes beginners make
- Fixing the line in the message instead of the line before it. The error line is where nil was used, not where it appeared.
- Adding
&.everywhere. The program stops crashing and starts giving blank output instead, which is harder to debug. - Misspelling a hash key, or mixing symbols and strings.
user["name"]returns nil when the key is:name. See the symbols answer linked below. - Ending a method with puts. The method then returns nil to its caller.
Check this in order
- Read the first line of the error: the method name, and
nilas the receiver. - Read the next line of the backtrace for the file and line number where it happened.
- On that line, find the object to the left of the dot. That is your nil.
- Print it:
p thing. Confirm it is nil rather than a string such as"nil". - Walk backward: where was it assigned? Did a hash lookup, a search, or a method call give it?
- Decide whether missing is allowed. If not, fix the source or use
fetch. If it is, use a default or&.. - Run again, and test the missing case on purpose.
For help printing values, see What is the difference between puts, print and p in Ruby?. For the key mismatch in item 3, see What is a symbol in Ruby, and when should I use one instead of a string?. If the nil came out of a block, What is a block in Ruby, and what does yield do? explains what a block hands back. The guide's Chapter 5 is a good companion once you start building classes, where nil instance variables are common.
Checked on 12 November 2026.
- A missing hash key or array position.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.