5

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
Flip
  • 6,233
  • 7
  • 46
  • 75
ayjay
  • 1,272
  • 2
  • 16
  • 25

2 Answers2

5

@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.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • 1
    How is `@one` different from `@two`? I understand @two belongs to instances of MyClass, but I don't understand how can an instance variable belong to the class object only but not to instances of a class. – ayjay May 02 '14 at 08:38
  • @ayjay Is it clear now ? – Arup Rakshit May 02 '14 at 08:50
0

The way I think about it is who should hold the information or be able to do a task (because it is the same for class methods vs instance methods).

class Person
  @@people = []

  def initialize(name)
    @name = name
    @@people << self
  end

  def say_hello
    puts "hello, I am #{@name}"
  end
end

# Class variables and methods are things that the collection should know/do
bob = Person.new("Bob") # like creating a person
Person.class_variable_get(:@@people) # or getting a list of all the people initialized

# It doesn't make sense to as bob for a list of people or to create a new person
# but it makes sense to ask bob for his name or say hello
bob.instance_variable_get(:@name)
bob.say_hello

I hope that helps.