Search⌘ K

Instance and Local Variables

Understand the difference between instance and local variables in Ruby, learn how variable scope affects method access, and see how instance variables are defined and used with the @ prefix. This lesson clarifies Ruby's variable handling compared to languages like JavaScript, helping you write effective, error-free code.

Instance variables

A careful reader would have already noticed the unknown prefix @ before the variable name. In Ruby, we can’t access variables out of the scope of the current method. The only exception is in the case of instance variables, which we’ll cover later. For example, the following Ruby code won’t be executed and will produce an error:

Ruby
# Error in code
x = 123
def print_x
puts x
end
print_x

The error message is: undefined local variable or method 'x' for main:Object (NameError). But, what is main? It turns out that any program in Ruby is wrapped by the main class. This is proven when we run the following program: