Wednesday, June 2, 2010

Instance and class variable get set methods

In ruby, instance variables have prefix '@' and class variables have prefix '@@'.

We have instance_variable_get and instance_variable_set methods from Object class and class_variable_get and class_variable_set methods from Module class in Ruby. Here is the typical usage of these methods from the ruby docs :-

----
class Fred
@@foo = 99
end

def Fred.foo
class_variable_get(:@@foo) #=> 99
end


----
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a) #=> "cat"
fred.instance_variable_get("@b") #=> 99


----
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_set(:@a, 'dog') #=> "dog"
fred.instance_variable_set(:@c, 'cat') #=> "cat"
fred.inspect #=> #Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\"

----

However, why do we need to specify the @ and @@ when the method names are smart enough to distinguish between whether the variable is an instance or a class variable. Why does a call to instance_variable_set require the "@" symbol in the first argument? Any idea ? Or has it been done with some purpose ?

No comments:

Post a Comment