Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the "@" instance variable belonging to the class object and "@@" class variable in Ruby? [duplicate]

Tags:

ruby

According to wikibooks...

  • @one below is an instance variable belonging to the class object (note this is not the same as a class variable and could not be referred to as @@one)
  • @@value is a class variable (similar to static in Java or C++).
  • @two is an instance variable belonging to instances of MyClass.

My questions:

What's the difference between @one and @@value?
Also, is there a reason to use @one at all?

class MyClass
  @one = 1
  @@value = 1

  def initialize()
    @two = 2
  end
end
like image 451
ayjay Avatar asked May 02 '14 08:05

ayjay


1 Answers

@one is an instance variable of the class MyClass and @@value is the class variable MyClass. As @one is an instance variable it is only owned by the class MyClass (In Ruby class is also object), not shareable, but @@value is a shared variable.

shared variable

class A
  @@var = 12
end

class B < A
  def self.meth
    @@var
  end
end

B.meth # => 12

non shared variable

class A
  @var = 12
end

class B < A
  def self.meth
    @var
  end
end

B.meth # => nil

@two is an instance variable of the instances of the class MyClass.

Instance variables are private property of objects, thus they wouldn’t share it. In Ruby classes are also objects. @one you defined inside a class MyClass, thus it is only owned by that class defining it. On the other hand @two instance variable will be created when you will be creating a object of the class MyClass, say ob, using MyClass.new. @two is only owned by ob, none other objects have any idea about it.

like image 55
Arup Rakshit Avatar answered Oct 02 '22 01:10

Arup Rakshit