Ruby 'Range.last' does not give the last value. What for?

When using triple point notation in a Range Ruby object, I get the following:

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

When I use the last method, I get:

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

I would expect 4

This is mistake? Or is there something I don't understand about the concept of a Range object?

+7
source share
2 answers

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

Note that without arguments, last will return an object that defines the end of the range, even if exclude_end? - true .

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

As Stefan said, your observed behavior is expected and documented.

If you want to get the last element to be enumerated by a range, without having to enumerate the entire range, you can use Enumerable#reverse_each

 irb> (0...5).reverse_each.first => 4 
+1
source

All Articles