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?
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.
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.
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.
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 ifexclude_end?
istrue
.(10..20).last #=> 20 (10...20).last #=> 20 (10..20).last(3) #=> [18, 19, 20] (10...20).last(3) #=> [17, 18, 19]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With