Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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 .

like image 410
Pawan Avatar asked Aug 27 '12 12:08

Pawan


People also ask

What is difference between local variable and instance variable in Ruby?

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.

What is the difference between and @@ in Ruby?

@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.

What is an instance variable in Ruby?

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.

Are instance variables inherited in Ruby?

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.


1 Answers

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
like image 170
Peter Roe Avatar answered Sep 22 '22 05:09

Peter Roe