Ranges
How would you describe the array [1,2,3,4,5]? Is it "the numbers 1, 2, 3, 4, and 5," or is it "the whole numbers from one to five"? Of course, either description fits, and neither is much more work than the other to express. But if you want to list "the whole numbers from one to ten thousand," it will take you a while to write them all out in a list. When you want to talk about a sequence of numbers that can be summarized by a starting point and an endpoint, why should we have to talk about all the points in between? We can use a range instead.
r = (4 .. 4) r.type #-> Range r.include? (1) #> true r.include? (5) #> false r.length #> 9 r.to_a #> [4, 3, 2, 1, 0, 1, 2, 3, 4]
Just as with hashes, to_a means "express as an array."
When a range is written as (start .. end), the endpoint is included. To exclude the endpoint, put an extra dot in the range specification.
(0 ... 5).to_a #-> [0, 1, 2, 3, 4]
Ranges can be used not just with numbers but with anything that has a well-defined sequence.
parts = ("Part A" .. "Part G") parts.length #> 7 parts.include? ("Part D") #> true
We'll see the usefulness of ranges when we talk about iterators tomorrow. For now it's important to understand that we can use a range instead of an array when we want to describe items in sequence. A range can both save us work and conserve memory (since Ruby keeps track of only the endpoints and doesn't store all the intermediate items).