Written by James BrittTechnically reviewed by Jim Freeze · Reviewed
A Ruby NameError means a name is undefined or invalid where you use it. Start with the exception class, the reported name and the first relevant line of your code. Then check spelling, scope, namespaces and loading. Fix the connection between the reference and its definition instead of suppressing the exception.
What appears to be a typo might really be a problem with scope. A variable elsewhere in the same file may be unavailable inside a method. Similarly, a class definition on disk is not usable until the program loads it. These differences determine which correction will help.

Read a Ruby NameError before changing code
First, read the exception header. An undefined local variable or method points toward a bare name Ruby could not resolve. An uninitialized constant points toward a class, module or another constant. By contrast, a wrong constant name indicates an invalid name supplied to a reflective operation.
Next, follow the backtrace to the relevant application line. Keep the original input while investigating. Changing both the input and the spelling can remove the symptom without explaining the cause. Save the failing case before simplifying it, so you can check the eventual repair against the original problem.
The examples ran in official Ruby 4.0.0 WASI, which identifies the tested runtime rather than the latest patch. Diagnostic formatting and suggestions can vary between environments. Therefore, these examples inspect exception properties instead of relying on identical full messages. No Rails application or native deployment was executed for this guide.
Start with spelling and the intended name
In the first example, the delivery charge exists, but the next reference swaps two letters. The handler displays the exception class and the misspelled name. Finally, the corrected reference prints the charge. Here, catching the exception helps demonstrate the failure; it is not an application fallback.
delivery_charge = 7
begin
delivery_chagre
rescue NameError => error
p error.class
p error.name
end
p delivery_charge
NameError
:delivery_chagre
7
Compare the reported name with its definition character by character. Check singular versus plural forms, letter swaps and capitalization. Also, ask whether you meant a local variable, an instance variable or a method. Similar spellings do not make them interchangeable: Ruby looks them up differently, and they have different lifetimes.
The DidYouMean project documents Ruby's spelling suggestions for missing names and method calls. Use a suggestion as a clue. Before accepting it, however, make sure the proposed name represents the value or operation you intended. A valid nearby name can still produce the wrong result for your code.
If the spelling was correct, stop renaming and examine the surrounding scope. First, search for the definition and determine whether execution reaches it. Then check whether its value is available at the failing location. Finding the same string elsewhere in your repository is merely the starting point.
Fix Ruby NameError across method boundaries
Methods defined with Ruby's ordinary method definition syntax do not capture local variables from the surrounding file. A helper immediately below an assignment can therefore cause confusion. Physical proximity does not imply shared local state. Instead, pass the required value to the helper as an argument.
Here, the first method attempts to use the outer delivery charge. The second accepts that charge directly. Passing the value makes the dependency explicit to callers. It also lets you test a different charge without changing global state or depending on previous console input.
delivery_charge = 7
def broken_charge
delivery_charge
end
begin
broken_charge
rescue NameError => error
p error.class
p error.name
end
def charge_for(delivery_charge)
delivery_charge
end
p charge_for(delivery_charge)
NameError
:delivery_charge
7
Rather than introducing a global variable to remove the exception, choose storage consistent with your design. An argument supplies a caller's value. An instance variable can represent an object's state, but adopting one changes the method's contract. You must also arrange for the appropriate initialization.
When debugging a Ruby NameError in a console session, try a fresh process or a smaller script. Earlier commands may have created variables or loaded classes that mask a missing dependency. In particular, rerun the repaired code without those earlier commands. That checks whether the program establishes its own inputs and definitions.
Check blocks and assignment order
A block can access existing outer local variables. However, a local first introduced inside a block does not become available outside it afterward. You do not need a separate scope rule for every iterator. Identify where the name first belongs, and then look at where you read it.
Ruby also recognizes local assignments during parsing, even when they never execute. As a result, the conditional assignment below yields nil rather than an unknown-name exception. Simply resolving a name does not mean the value is useful. The program still needs a path that assigns the intended value.
discount = 5 if false
p discount
nil
A variable containing nil is still a known local variable. Conversely, a misspelled bare reference may trigger lookup as a method because Ruby has not recognized a local assignment for it. That explains the combined wording about a variable or method. The message does not ask you to invent both; decide which kind of name your code intended to use.
Initialize clearly when a value must survive a conditional or loop. Alternatively, return the operation's result and assign it outside. Use a default only when it makes sense for the application. Replacing every missing value with zero or a blank string could hide a different logic bug.
Resolve constants and namespaces
For an uninitialized constant, check the entire constant path. This example defines a parcel class within a shipping module. A reference to the top-level parcel constant fails, while the qualified reference finds the class. Thus, the repair identifies the intended namespace without moving the definition.
module Shipping
class Parcel
end
end
begin
Parcel
rescue NameError => error
p error.class
p error.name
end
p Shipping::Parcel.name
NameError
:Parcel
"Shipping::Parcel"
Capitalization matters too: constants start with an uppercase letter, whereas typical local names start lowercase. If a reflective constant operation rejects an invalid name, loading another file will not fix its spelling. First distinguish an invalid name from a valid name that lacks a definition.
Once the constant path looks right, determine how its defining file enters the program. An ordinary script may need an explicit require operation. If loading itself fails, investigate that file or dependency first. Otherwise, you could mistake a consequence of incomplete startup for an independent naming problem.
The official Rails autoloading guide explains the relationship between filenames, namespaces and constants. Check the constant expected from the file and the application's autoload roots. Do not manually require application files managed by the autoloader. These are source-based Rails checks, not evidence from running a Rails application.
Separate Ruby NameError from NoMethodError
Because NoMethodError is a subclass of NameError, rescuing the broader class catches missing-method errors too. That distinction matters during diagnosis. An explicit object can lack the requested operation even though the variable holding it exists. The next example demonstrates both the inheritance relationship and the actual exception class.
p NoMethodError < NameError
begin
"parcel".missing_shipping_action
rescue NameError => error
p error.class
end
true
NoMethodError
Our Ruby NoMethodError guide covers receiver and method checks in more detail. Use that path when an exception identifies a missing operation on an object. For a bare unresolved name, begin with local scope and spelling. Always inspect the actual class rather than guessing from a message fragment.
Keep production rescue clauses narrow. A broad handler around an entire workflow can mask a later typo and treat it as success. If a fallback is intentional, document the expected failure and test that boundary. Otherwise, fix the lookup and allow unexpected failures to remain visible.
Try it: which total exists afterward?
Before revealing the explanation, decide whether this snippet prints a total or reports a missing name. Then compare it with the corrected version, which establishes an outer total before entering the block. The amount stays the same; the location of the first assignment changes.
1.times do
total = 12
end
begin
p total
rescue NameError => error
p error.class
end
Reveal the scope explanation and corrected example
NameError
The first snippet reports NameError because its total is new inside the block. The second prints the calculated total because the block updates an existing outer local. Simply placing the first snippet earlier in a file would not make that block local available afterward.
total = 0
1.times do
total += 12
end
p total
12
For a follow-up, change the starting total and predict the new result. Then move the calculation into a method that accepts the starting amount. This ties the rules together: a block can share an existing outer local, while an ordinary method needs an explicit input.
Takeaway
Fix a Ruby NameError by identifying where the missing name belongs and how the program should define it. Check spelling, pass method inputs explicitly, qualify constants and verify loading. Finally, rerun the original failing input and add a focused regression check. Silence alone does not prove the repair is correct.
