Ranges

A range represents an interval — a start value, an end value, and everything in between. Ranges are written with two dots, usually inside parentheses. Here we iterate over one with each:

$ irb
>> (0..3)
=> 0..3
>> (0..3).class
=> Range
>> (0..3).each do |i|
?>   puts i
>> end
0
1
2
3
=> 0..3
>>

Via the method to_a you can generate an array from a Range:

>> (0..3).to_a
=> [0, 1, 2, 3]
>>

A range can be generated from objects of any type. Important is only that the objects can be compared via <⇒ and use the method succ for counting on to the next value. So you can also use Range to represent letters:

>> ('a'..'h').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h"]
>>

As alternative notation, you may sometimes come across Range.new(). In this case, the start and end points are not separated by two dots, but by a comma. This is what it looks like:

>> (0..3) == Range.new(0,3)
=> true
>> exit