Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Local Variables versus Instance Variables

Tags:

ruby

while learning Rails, I keep hearing Local vs Instance but I can't find a definition of the two & the differences. And I'd like to avoid making assumptions.

What are the two and how are they different?

Thanks

like image 520
AnApprentice Avatar asked Sep 21 '10 05:09

AnApprentice


People also ask

What is the difference between instance variable and local variable?

Difference Between Instance Variable and Local Variable An instance variable is a variable declared in a class, but outside a method. These variables represent the object state throughout the class. Any object of that class has its own copy of that instance variable.

What are instance variables in Java?

Instance Variable: These variables are declared within a class but outside a method, constructor, or block and always get a default value. These variables are usually created when we create an object and are destroyed when the object is destroyed.

What is a local variable in Java?

A local variable is a variable that is declared inside a method or a constructor. Local variables are created when entering the method or a constructor. Similarly, exiting the method or a constructor destroys these variables. Therefore, local variables are only visible within the declared method or the constructor.

Are variables defined inside or outside of a class?

They are defined in class but outside the body of methods. They are defined as a type of variable declared within programming blocks or subroutines. These variables are created when an object is instantiated and are accessible to all constructors, methods, or blocks in class.


2 Answers

The main difference between local and instance variable is that local variable is only available in controller, where as instance variable is available in corresponding views also. The controller and views do not share local variables.

Thanks, Anubhaw

like image 96
Anubhaw Avatar answered Sep 20 '22 12:09

Anubhaw


The main differences between local and instance variables are as follows

  1. local variable has its scope restriction i.e not available to another methods where as instance available to another
  2. local and instance variable is also available in view
  3. instance variable is separate for each object
like image 27
Hitesh Avatar answered Sep 20 '22 12:09

Hitesh