Ranges

Ruby supports ranges by means of the .. (inclusive) and ... (exclusive) operators. For example, the range 1..12 includes the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, inclusive. However, in the range 1...12, the ending value 12 is excluded; in other words, the effective numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11.

The === method determines whether a value is a member of, or included in a range:

(1..25) === 14 # => true, in range
(1..25) === 26 # => false, out of range
(1...25) === 25 # => false, out of range (... used)

You can use a range to do things like create an array of digits:

(1..9).to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also create a range like this:

digits = Range.new(1, 9)
digits.to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

Get Ruby Pocket Reference 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.