Crystal: [RFC] Endless ranges

Created on 10 Dec 2018  路  9Comments  路  Source: crystal-lang/crystal

Ruby 2.6 introduces endless ranges:

[1, 2, 3, 4, 5][2..] # => [3, 4, 5]

I think it's a small nice addition. It removes the need to write -1 and the confusion of 2..-1 vs 2...-1 (in the above snippet 2.. and 2... would give the same result).

Ruby implements this by having the end of the range be nil. We could do the same.

The only "ugly" thing about it is that you always have to write that range inside parentheses, brakcets, or another expression (you can't just write a = 1.. because the parser will wait for the end value, and a newline makes it still expect the end value). But one can write a = 1..nil so it's a minor issue (plus these ranges are mostly useful in nested positions).

I don't think it's too hard to implement this.

Thoughts?

(side note, I also thought about having ..3 meaning "from the start", but it's not that useful because one could always put a zero there, it's always zero, and then there's the confusion of which zero is it (int or float?))

Most helpful comment

It seems Ruby is adding beginless ranges too :-)

All 9 comments

The only "ugly" thing about it is that you always have to write that range inside parentheses

Well, ranges often need parentheses already, like (a..b).to_a.

That's true. I guess the only corner case is in assignments, but you can still use parentheses or nil there.

I also thought about having ..3 meaning "from the start", but it's not that useful

Ruby tracker has such [proposition]:

case release_date
when ..1.year.ago
  puts "ancient"
when 1.year.ago..3.months.ago
  puts "old"
when 3.months.ago..Date.today
  puts "recent"
when Date.today..
  puts "upcoming"
end

human readable ?

In Crystal you can use .<(1.year.ago)

Yes, though I agree that the use cases for ..end are nice. I'll play with these and try to send a PR. No need to merge it if it's not needed.

@sudo-nice except that you need parentheses around the first and last when

Why not, not against this syntax. Personally I would love having nillable ranges like ary[3..7]?

It seems Ruby is adding beginless ranges too :-)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

relonger picture relonger  路  3Comments

nabeelomer picture nabeelomer  路  3Comments

costajob picture costajob  路  3Comments

Papierkorb picture Papierkorb  路  3Comments

pbrusco picture pbrusco  路  3Comments