Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

range

ruby

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?

like image 643
Paul Verschoor Avatar asked Jul 13 '12 09:07

Paul Verschoor


People also ask

How do you create a range in Ruby?

Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.

Is a range an array in Ruby?

Yes, the method does look like an array class. However, you need to add a pair of parenthesis to let Ruby know you are using the Array method and not the class. The resulting value is the range of values in an array format.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

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]
like image 73
Stefan Avatar answered Nov 10 '22 12:11

Stefan