text
Class instance variable vs Class variable vs Object variable in Ruby
class Foo
@a = 123 # Class instance variable (1)
@@a = 456 # Class variable (2)
def foo
p @a # => nil not 123 or 456 - Ordinary instance/object variable (3)
end
end
- (3) is an ordinary instance variable (which, not having been initialized, has a value of nil), it belongs to an instance of class Foo.
- (2) is a ordinary class variable unique and accessible to all object instances of class Foo
- (1) belongs to the class object Foo, which is an instance of Class class.
The last one (1) is quite strange for someone coming from languages like Java. A good rule of thumb to know to which object a variable is attached to is:
The first mention of an @-prefixed variable creates the instance variable in the current object, self.
Therefore, since everything is an object in Ruby, if you declare a @-variable when self is the class, the variable will be attached to it.
blog comments powered by Disqus