Ruby: difference between instance and local variables in Ruby

Possible duplicate:
Rails and class variables

Can someone please tell me what is the difference between Ruby instance variables and local variables?

As far as I know, both instance variables and local variables are the same, and both are declared inside the method itself and except that instance variables are denoted by @.

+6
ruby
source share
1 answer

This is a scope issue. A local variable is visible / applicable only in the method in which it is defined (i.e., it disappears when the method returns).

On the other hand, an instance variable is visible elsewhere in the instance of the class in which it was defined (this is different from a class variable that is shared between all instances of the class). However, keep in mind that it is important when defining an instance variable. If you define an instance variable in one method, but try to use it with another method before calling the first, your instance variable will be nil:

def method_one @var = "a variable" puts @var end def method_two puts @var end 

@var will have a different meaning 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 
+11
source share

All Articles