Fix a Ruby "NameError: undefined local variable" Error

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

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

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

NameError: undefined local variable or method `a' for main:Object (with various identifiers in place of 'a').

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

An Example of the Error

This code will generate the error above:

puts a

Since the variable a hasn't yet been assigned to anything, Ruby will raise a NameError exception.

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:

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.

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.