开发者

Range.to_a example in "Programming Ruby"

thanks for checking this que开发者_如何学Gostion out. This is my first question here so any help/criticism appreciated. I'm working my way (beginner) through the free online version of Programming Ruby: The Pragmatic Programmer's Guide, version 1. The following example does not do (when I do it) what the book says it should:

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

Should do the following, according to the book, in irb:

medium = VU.new(4)..VU.new(7)
medium.to_a     »   [####, #####, ######, #######]
medium.include?(VU.new(3))  »   false

But what does happen for me is medium.to_a returns with an array of the VU objects like so:

#<VU:0x9648918>                                                              
#<VU:0x96488b4>                                                              
#<VU:0x964888c>                                                              
#<VU:0x9648878>

And that makes sense to me (I think). What doesn't make sense to me is the book's assertion that what should be returned is an array of '#'s. Wouldn't we need to invoke the inspect method in order to get those "#'s?

Thanks! Ian


Is that what you see in irb? inspect is called implicitly on return values in irb. You are correct in that array is filled with VU objects, but what should be displayed is the output of inspect for those objects.

> x = VU.new(5)
=> #####
> x.class
=> VU
> x.succ
=> ######
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜