Ruby 'Range.last' does not give the last value. Why?

拈花ヽ惹草 提交于 2019-12-01 00:27:31

问题


When using the triple dot notation in a ruby Range object, I get this:

(0...5).each{|n| p n}
0
1
2
3
4

When I use the 'last' method I get:

(0...5).last
 => 5 

I would have expected 4

Is this is a bug? Or is there something I don't understand about the the concept of a Range object?


回答1:


This is by design. The Ruby 2.0 documentation is more specific:

Note that with no arguments last will return the object that defines the end of the range even if exclude_end? is true.

(10..20).last      #=> 20
(10...20).last     #=> 20
(10..20).last(3)   #=> [18, 19, 20]
(10...20).last(3)  #=> [17, 18, 19]



回答2:


As Stefan has answered your observed behavior is expected and documented.

If you want to obtain the last element which would be enumerated by the range without having to enumerate the whole range, you could use Enumerable#reverse_each

irb> (0...5).reverse_each.first
=> 4


来源:https://stackoverflow.com/questions/11467846/ruby-range-last-does-not-give-the-last-value-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!