In prag ruby the purchased copy, the following code fragment is shown.
Look at where I added the >>>>. That line VU.new(@volume.succ). What I
think it should do is create a new object instance of the class. What
it does though is it increments the attribute @volume on an existing
object that uses the succ method.
I have verified that it does not create a new object by using
myObject.object_id. I am sure this is basic oop stuff but I do not
think I have seen it. Why does this happen like this?
I would have used an accessor to set the @volume. I am surprised by the
use of new here.
Thanks for your insight.
_Nathan
class VU
include Comparable
attr :volume
def initialize(volume) # 0…9
@volume = volume
end
def inspect
‘#’ * @volume
end
Support for ranges
def <=>(other)
self.volume <=> other.volume
end
def succ
raise(IndexError, “Volume too big”) if @volume >= 9
VU.new(@volume.succ) <<<<<
end
end