Why are these two equivalent?
(10..20).last #=> 20
(10...20).last #=> 20
This sounds like a duplicate of Ruby 'Range.last' does not give the last value. Why?, but the answers to that question simply say it's by design. Why is it designed like that? What is the purpose of ..
and ...
returning the same values for last
when everything else is different?
I'll answer your question with a question: what is the last value of 0.0...1.0
?
In general, not every Range is enumerable. For such ranges with an excluded end, there really is no meaningful last
value other than the value used to define the end of the range.
Note also that you can enumerate inclusive ranges where last
is not the last value enumerated!
(0..3.2).to_a.last
# 3
(0..3.2).last
# 3.2
(0..Float::INFINITY).to_a.last
# don't wait up for this one
The motivation of the design is that "the value used to define the end of a range" is not identical to "the last value enumerated by a range". last
gives you the former.
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