Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (10..20).last the same as (10...20).last [duplicate]

Tags:

ruby

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?

like image 434
K - Avatar asked Sep 19 '14 15:09

K -


1 Answers

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.

like image 197
Max Avatar answered Sep 19 '22 07:09

Max