Ruby:Difference Between Instance and Local Variables in Ruby

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

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">

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!

Difference between local and instance variables in ruby

Setting @variable = nil destroys the reference to the object that the instance variable once pointed to. When there are no more remaining references to an object, it should be collected by the garbage collector eventually. I say "eventually" because the GC is somewhat unpredictable. However, it's easy to have a memory leak by a "dangling reference" and possibly (depending on how the GC is implemented) circular references. What else refers to this object?

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.

Difference between various variables scopes in ruby

  1. Class variables are the same for all instances, because they're class variables–associated with the class. Everything access the same variable, including each instance.

  2. No. Local variables are just that–local. They may be local to a function, or local to the class declaration, which is different than being a class variable. Locals in a class declaration go out of scope when the class declaration ends.

  3. That's because they're exactly the same–they're global. Global state is always evil; this is not a property of the language or environment. That said, some global state may be required–that's just the way it is. It makes sense to use global state when there's global state. The trick is to use global state properly, which is sometimes a non-trivial endeavor.

  4. That's just how Ruby is.

  5. One has already been given by Chris.

  6. I would think this question would be largely self-answering. Global when the entire world needs access. Instance when it's specific to a class instance. Local when it's only required in a local scope (e.g., a method, a block (note differences between 1.8 and 1.9 with regard to block scope), etc.) Constant when the variable isn't supposed to change. A class variable when it's something that either every instance needs, or if exposed via a class method, something tightly associated with a class.

  7. There is no "most use-cases", it totally depends on what you're doing with the variable. And public isn't the de facto choice in Java–it depends on the entity in question. Default Java scope is package-private (methods, properties). Which to use in Ruby depends entirely upon the use-case, noting that as with Java, and even more easily in Ruby, things can be circumvented.

Difference between local and instance variables

instance variables exist as long as the class exists

They exist as long as the object exist. Instance variables are per-object, not per-class.

what happens if you declare a local variable in the class scope without prefixing it with @?

Then the variable is in scope within the class definition, but not within any defs inside that class definition as those introduce a new scope.

Doesn't that implicitly make it an instance variable, even though you didn't use an @ to declare it as one?

No.

If you use define_method instead of def to create methods, the local variable will be accessible within the methods, but since the variable only exists once (not once per object), they'd act more like class variables than instance variables in that case. I also can't think of a good reason why you'd use them that way.

Rails - Local Variables versus Instance Variables

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

Difference between Ruby's class variable and instance variable

I think "instance variable, class variable and the difference between them in ruby" has a good explanation of the difference between local, instance and class variables.



Related Topics



Leave a reply



Submit