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
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With