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
No comments:
Post a Comment