Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata