7

Possible Duplicate:
Rails and class variables

Could anybody please tell me whats the difference between Ruby Instance variables and Local variables ?

As far as i know both Instance variables and Local variables are same , and both are declared inside the method itself and except that instance variables are denotated using @ symbol .

Community
  • 1
  • 1
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • I have an explanation on this here: http://stackoverflow.com/questions/11523547/rails-and-class-variables/11523632#11523632 – Frost Aug 27 '12 at 12:49

1 Answers1

13

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
Peter Roe
  • 446
  • 3
  • 6
  • 1
    great answer - i would like to add that if a local variable (e.g. localVar) is declared in method_one, then it cannot be called from method_two. – BenKoshy Apr 25 '16 at 01:58