16

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

0

2 Answers 2

36

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

Sign up to request clarification or add additional context in comments.

2 Comments

Example, @name = "Ruby_rails" is an instance variable and name = "Ruby_rails" is an local variable. Thanks......
In case this helps anyone: It is possible to set local variables for your templates through the controller this way: render :index, :locals => { :stuff => @stuff }
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.