Labs ICT
โญ Pro Login

Ranges

Sequences of values.

Ruby Ranges

Ranges are concise and expressive. Use two dots .. for inclusive ranges, and three dots ... for exclusive (the end value is excluded).

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

You can create character ranges too. They work exactly as you'd think:

("a".."e").to_a   # => ["a", "b", "c", "d", "e"]
("A".."F").to_a   # => ["A", "B", "C", "D", "E", "F"]

Check if a value is inside a range with include?:

(1..10).include?(5)    # => true
("a".."z").include?("m")  # => true

Need an infinite range? Pair a start with Float::INFINITY and use lazy so it doesn't try to create a billion elements at once:

(1..Float::INFINITY).lazy.select(&:odd?).take(5).to_a
# => [1, 3, 5, 7, 9]

Ranges work beautifully in case statements for pattern matching on values:

score = 85

grade = case score
        when 90..100 then "A"
        when 80..89  then "B"
        when 70..79  then "C"
        else "F"
        end

They're also used in for loops and enumeration. Simple, readable, very Ruby.

Try it Yourself ->

๐Ÿงช Quick Quiz

What creates an inclusive range?