Saturday, June 2, 2007

Calling attribute setters from module

The question is, what is the output of the following ruby code:


module A
def set_x(y)
x=y
end
end

class B
attr_accessor :x
end

b = B.new
b.x=1
b.set_x(2)
puts b.x


The output is 1, and for first i expected the output to be 2.

A.set_x creates a new local variable x instead of calling the attribute setter, which is proabably a wise decision. Otherwise a module method that intends to use a local variable, might end up using an attribute setter. (If the class which includes the module has one.)

The workaround is to tell the module that you want to access the attribute setter with self.:


module A
def set_x(y)
self.x=y
end
end