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

后端 未结 2 1632
星月不相逢
星月不相逢 2021-01-12 02:50

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

2条回答
  •  猫巷女王i
    2021-01-12 03:26

    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
    

提交回复
热议问题