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.” ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.