1. Computing

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

By

Problem: You encounter an error reading NameError: undefined local variable or method `a' for # or NameError: undefined local variable or method `a' for main:Object (with various identifiers in place of 'a').

Solution: You've referred to a local variable that doesn't yet exist. In Ruby, you don't have to declare variables, but you have to assign something to them before they can be referred to. For instance, the following code will generate the error above.


puts a

Since the variable a hasn't yet been assigned to, Ruby will raise a NameError exception. Instead, variables must be assigned to before they can be used.


a = 10
puts a

So why are you getting this error? The obvious answer is you're referring to a variable that hasn't yet been created. This is most often due to a typo or while refactoring code and renaming variables. So look back over your code, try 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, as if it's wrong in one place, it may be wrong in others.

©2014 About.com. All rights reserved.