Ranges

Range is another great class. Ranges represent intervals of numbers. On the next page is just a quick glance at some of the methods ranges have.

# This is your range literal.
letters = ​'a'​..​'c'
# Convert range to array.
puts([​'a'​,​'b'​,​'c'​] == letters.to_a)
# Iterate over a range:
(​'A'​..​'Z'​).each ​do​ |letter|
print letter
end
puts
god_bless_the_70s = 1970..1979
puts god_bless_the_70s.min
puts god_bless_the_70s.max
puts(god_bless_the_70s.include?(1979 ))
puts(god_bless_the_70s.include?(1980 ))
puts(god_bless_the_70s.include?(1974.5))
true
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1970
1979
true
false
true

Do you really need ranges? No, not really. It’s the same with hashes and times, I suppose. You can program fairly well without them (and most languages ...

Get Learn to Program, 2nd Edition 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.