Rails - Local Variables versus Instance Variables
The main differences between local and instance variables are as follows
- local variable has its scope restriction i.e not available to another methods where as instance available to another
- local and instance variable is also available in view
- instance variable is separate for each object
What is the difference between using local variable or instance variable in an Rails API?
The performance difference will be negligible.
But there's two competing guidelines at work. One is "Always use the weakest construction." Don't use double "quotes" if you can use single 'quotes'. Don't use a regular expression if you can use String#index. Don't use an instance variable if you can use a local variable.
The other guideline is "Design for testing." If you use an instance variable, your test can inspect it with assigns(:user)
. That rule trumps the "weakest construction" rule. So use an instance variable, and write lots of automated tests!
Normal Variables Vs Instance variable in Ruby, Whats the difference?
A normal variable has scope only within the current context; an instance variable has scope throughout one instance of a class. In your case they're confused because the context is main
, which acts as an instance of Object
.
Consider the following, which may make things clearer
class User
def set_name
@name = "Bob"
surname = "Cratchett"
end
def hi
puts "Hello, " + @name
end
def hello
puts "Hello, Mr " + surname
end
end
irb(main):022:0> u = User.new
=> #<User:0x29cbfb0>
irb(main):023:0> u.set_name
irb(main):024:0> u.hi
Hello, Bob
=> nil
irb(main):025:0> u.hello
NameError: undefined local variable or method `surname' for #<User:0x29cbfb0 @name="Bob">
confused between instance variable and local variable
In your first example you created a local variable updated
, that is only accessible within the scope of the block it is defined in. Meaning, it is available only within Prime.each(number) do end
block.
In your second example you created instance variable @updated
.
without creating a class how my instance variable ( @updated) is
working
It is because in Ruby everything occurs in the context of some object. Even though you did not created a class, you are being in the top-level context, in the context of object main
.
Thus, any instance variables defined within top-level are instance variables of this object main
.
So going back to your issue, to overcome it you'll want to just define the updated
local variable outside the Prime.each(number) do end
block:
def prime_large(number)
arr_prime = []
updated = nil # initialize local varialbe
Prime.each(number) do |x|
new_arr_prime = arr_prime.push(x.to_s)
updated = new_arr_prime.select { |y| y.reverse == y } # assign new value
end
p updated.max
end
p prime_large(1000)
To test it you can open irb or pry and check it yourself:
self # the object in the context of which you are currently
#=> main
self.class # main is an instance of class Object, any methods defined
# within main are added to Object class as instance methods
#=> Object
instance_variables # list of it's instance variables, none yet created
#=> []
@variable = 1 # create and instance variable
#=> 1
instance_variables # now created variable occurs in the list of current object's instance variables
#=> [:@variable]
def hello; :hello end # define method
#=> :hello
self.class.public_instance_methods(false) # list instance methods defined in Object
#=> [:hello]
What you now want to read about is lexical scopes in Ruby.
In rails, does it matter to use local variable or instance variable in action methods
Mostly we need to use instance variable in following cases,
- When we need to access the variable from view
- If we are calling a method from the action, instead of returning a value, we can directly update the variable from the called method.
Why should we use instance variable if our job can be done with a local variable.
Ruby : Difference between Instance and Local Variables in Ruby
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
Views: is it better to set instance variables or pass in locals?
In Rails, it's best practice to pass the instance variables to your views. Rails developers are used to it, it's familiar, it's less typing, it works.
Yet, my personal preference is to pass locals
to render
because it makes your view variables more explicit. It also has a benefit of raising a "no method" exception if you mistype a variable rather than getting a "nil" exception when using instance vars.
I'm not sure there is going to be much difference in performance either way. Might be interesting running some benchmarks. But if you're using Rails, then view rendering speed is probably not your top concern.
Note that if you use an instance var in your controller to memoize a method's result (say to cache an expensive calculation), than that instance var "leaks" into your view. You probably didn't need it in your view, but you still get it (because Rails exposes any instance vars in controllers to your views). Thus, passing local vars is more explicit in communicating "my view relies on this variable")
Related Topics
How to Overwrite a Printed Line in the Shell with Ruby
How to Access Attributes Using Nokogiri
Selenium Scroll Element into (Center Of) View
Converting from Xml Name-Values into Simple Hash
Assign/Replace Params Hash in Rails
Render Three Different Partials Depending on Button Clicked
Escape Single Quote in Xpath with Nokogiri
Ruby on Rails Send_File Doesn't Work Until I Refresh the Page
Ruby | Find a Way to Find an Exception on the Same Word to Capitalize
How to Round a Time Down to the Nearest 15 Minutes in Ruby
How to Add to a Serialized Array
Get All Instance Variables Declared in Class
Why Is Enumerable#Each_With_Object Deprecated
Windows/Ruby/Rails Install --- .Cannot Load Such File -- SQLite3/Sqlite3_Native Windows
How to Customize the Table Builder Plugin for a Week Calendar
Convert (Decode) Hexadecimal String to Binary String
How to Create Symbol (Hash Key) from Association, Using New Ruby (1.9) Hash Syntax