Skip to content

Ruby error: undefined local variable or method

Sean Lerner edited this page Apr 5, 2017 · 9 revisions

If you type a word into ruby, and it's not a keyword (e.g. if, else, def, class, etc.), ruby will first try to treat the word as a variable if it was previously defined, and if not, try to call a method using that word.

How To Fix

Step 1: Determine if you meant to type a string

Ruby treats text between single or double-quotes as strings. Did you forget to put the text between quotes and now ruby thinks it's a variable or method?

For example, if I have the following code:

name = sean

Ruby would think that sean is a method or variable. What I really need is quotes around 'sean':

name = 'sean'

Example

/path/to/my_program.rb:30:in `my_method':
undefined local variable or method `my_variable_or_method_name'
for #<MyProgram:0x007fd229275440> (NameError)

It expected that this code existed in the same method before it got to the error:

my_variable_or_method_name = "my variable value"`

or that the method was defined in the same class:

def my_variable_or_method_name
  # code...
end
Clone this wiki locally