Ranges with 2 or 3 dots

Ruby ranges with either two or three periods are valid ranges.

(1..5).class # => Range
(1...5).class # => Range
("a".."z").class # => Range
("a"..."z").class # => Range

However, the 2 dot and 3 dot formats produce different ranges. The 3 dot ranges exclude the end value (eg. they are not inclusive). While the 2 dot ranges are inclusive (they include the highest number).

Here is a simple example:

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

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

("a".."j").to_a
# => ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

("a"..."j").to_a
# => ["a", "b", "c", "d", "e", "f", "g", "h", "i"]


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *