Fix a Ruby "NameError: undefined local variable" Error

You'll see an error like this if you're referencing nonexistent variables

Picture of an error message on a computer screen
Epoxydude/Getty Images

In Ruby, you don't have to declare variables, but you do have to assign something to them before they can be referred to.

If you're referring to a local variable that doesn't yet exist, you may see one of two errors.

Ruby NameError Messages

NameError: undefined local variable or method `a' for # 
NameError: undefined local variable or method `a' for main:Object

Note: There might be various identifiers in place of 'a' above.

This is an example where the code will generate the Ruby "NameError" message since the variable a hasn't yet been assigned to anything:

puts a

How to Fix the Error

Variables must be assigned before they can be used. So, using the example from above, fixing the error is as simple as doing this:

a = 10
puts a

Why You're Getting This Error

The obvious answer is that you're referring to a variable that hasn't yet been created. This is most often due to a typo but may happen when refactoring code and renaming variables.

You might also see the "NameError: undefined local variable" Ruby error if you intended to enter a string. Strings are understood when they exist between quotes. If you didn't use quotes, Ruby will think you meant to reference a method or variable (that doesn't exist) and throw the error.

So, look back over your code to see what this variable is supposed to be referring to, and fix it. You may also want to search for other instances of the same variable name in the same method - if it's wrong in one place, it may be wrong in others.

Format
mla apa chicago
Your Citation
Morin, Michael. "Fix a Ruby "NameError: undefined local variable" Error." ThoughtCo, Aug. 26, 2020, thoughtco.com/nameerror-undefined-local-variable-2907927. Morin, Michael. (2020, August 26). Fix a Ruby "NameError: undefined local variable" Error. Retrieved from https://www.thoughtco.com/nameerror-undefined-local-variable-2907927 Morin, Michael. "Fix a Ruby "NameError: undefined local variable" Error." ThoughtCo. https://www.thoughtco.com/nameerror-undefined-local-variable-2907927 (accessed March 28, 2024).