Jun'uary
Jan'uary » 日志 » Using Accessors within a Class
Using Accessors within a Class
Jan 发表于 2006-12-04 14:57:54
Why did we write self.left_channel in the example? Well, writable attributes have a hidden gotcha. Normally, methods within a class can invoke other methods in the same class and its superclasses in functional form (that is, with an implicit receiver of self).
However, this doesn’t work with attribute writers. Ruby sees the assignment and decides that the name on the left must be a local variable, not a method call to an attribute writer.
However, this doesn’t work with attribute writers. Ruby sees the assignment and decides that the name on the left must be a local variable, not a method call to an attribute writer.
class BrokenAmplifierWe forgot to put “self.” in front of the assignment to left_channel, so Ruby stored the new value in a local variable of method volume=; the object’s attribute never got updated. This can be a tricky bug to track down.
attr_accessor :left_channel, :right_channel
def volume=(vol)
left_channel = self.right_channel = vol
end
end
ba = BrokenAmplifier.new
ba.left_channel = ba.right_channel = 99
ba.volume = 5
ba.left_channel ! 99
ba.right_channel ! 5
相关日志:
收藏:
QQ书签
del.icio.us
订阅:
Google
抓虾
