Ranges

What Is a Range in Ruby?

The Range class is a built-in Ruby object. Its instances (ranges) denote sequential collection of values with a indicated beginning and end.

Initializing Ranges

An instance of the Range class can be created with a new method but more often literals - .. and ... are used. A range initialized with .. includes the end value and the range initialized with ... does not.

1..5 # Includes values 1, 2, 3, 4 and 5.
(1..5).to_a # => [1, 2, 3, 4, 5]

1...5 # Includes values 1, 2, 3 and 4.
(1...5).to_a # => [1, 2, 3, 4]

Out-of-the-box ranges can also be initialized with letters as underlying values instead of integers.

'a'..'e' # Includes values 'a', 'b', 'c', 'd' and 'e'.

<=>

Ranges can be initialized for any Ruby objects that are capable of being compared with <=> operator.