Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normal Variables Vs Instance variable in Ruby, Whats the difference?

Tags:

variables

ruby

Consider the following sample ruby class

class User
  def hello
    puts "hello"
  end
end

now, for initialization. there are two ways

normal variable

1.9.3p125  > tr = User.new
 => #<User:0x98778c4>
1.9.3p125  > tr.hello
 Hello world
 => nil`

Instance variables:

1.9.3p125 > @tr = User.new
 => #<User:0x9890f2c>
1.9.3p125 > @tr.hello
Hello world
 => nil

Now, in both cases it works the same. so what is the difference between normal variable vs instance variable?

like image 240
CuriousMind Avatar asked Apr 23 '12 12:04

CuriousMind


2 Answers

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">
like image 65
Chowlett Avatar answered Oct 02 '22 01:10

Chowlett


The normal variable is called a local variable and is local to the code construct in which it was defined (if you define it in a method it cannot be accessed outside that method).

An instance variable is local to a specific instance of an object. If one object changes the value of the instance variable, the change only occurs for that object.

There are also class variables local to all instances of the class:

@@class_variable = 'a class variable'

And global variables accessible from anywhere within the program:

$global_variable = 'a global variable'

like image 21
DanS Avatar answered Oct 02 '22 02:10

DanS