6.2. Ranges

Ranges are fairly intuitive, but they do have a few confusing uses and qualities. A numeric range is one of the simplest:

digits = 0..9
scale1 = 0..10
scale2 = 0...10

The .. operator is inclusive of its endpoint, and the ... is exclusive of its endpoint. (This may seem unintuitive to you; if so, just memorize this fact.) So digits and scale2 shown in the preceding example are effectively the same.

But ranges are not limited to integers or numbers. The beginning and end of a range may be any Ruby object. However, not all ranges are meaningful or useful, as we shall see.

The primary operations you might want to do on a range are to iterate over it, convert it to an array, or determine whether it includes a given object. Let’s look at ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition 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.