Ranges in Ruby

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.

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.