Range Literal
We can define inclusive (..
) and exclusive (...
) ranges in Ruby with the range literal syntax.
These ranges are often of integers:
> (3..9).to_a
=> [3, 4, 5, 6, 7, 8, 9]
> (3...9).to_a
=> [3, 4, 5, 6, 7, 8]
but we can also do ranges of other classes, like String
, as long as they implement the <=>
operator.
> ('a'..'g').to_a
=> ["a", "b", "c", "d", "e", "f", "g"]
There are also beginless and endless ranges:
> (..10)
=> nil..10
irb(main):166> (10..)
=> 10..
And why not also a range that has no beginning or ending:
> nil..nil
=> nil..