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 .
A local variable can be used only within the method in which it is defined (or, when the variable is defined at the top level, only outside of any method). An instance variable can be used from any method that is called on the same instance.
@variable is only directly accessible within the class methods of the class it's defined in, whereas @@variable is shared between a class and all its subclasses and ancestors.
An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.
Instance variables are not inherited. If a method is written in the subclass with the same name and parameters as one in the parent class, the super class' method is overwritten.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With