Ruby : Difference between Instance and Local Variables in Ruby [duplicate]

It’s a matter of scope. A local variable is only visible/usable in the method in which it is defined (i.e., it goes away when the method returns).

An instance variable, on the other hand, is visible anywhere else in the instance of the class in which it has been defined (this is different from a class variable, which is shared between all instances of a class). Keep in mind, though, that when you define the instance variable is important. If you define an instance variable in one method, but try to use it in another method before calling the first one, your instance variable will have a value of nil:

def method_one
  @var = "a variable"

  puts @var
end

def method_two
  puts @var
end

@var will have a different value depending on when you call each method:

method_two() # Prints nil, because @var has not had its value set yet

method_one() # Prints "a variable", because @var is assigned a value in method_one

method_two() # Prints "a variable" now, because we have already called method_one

Leave a Comment