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 don’t have anything like them, anyway). But it’s all about style, about intention, and about capturing snapshots of your brain right there in your code.

And this is all just the tip of the iceberg. Each of these classes has way more methods than I have shown you, and this isn’t even a tenth of the classes that come with Ruby. But you don’t really need most of them…they are just time-savers. You can pick them up gradually as you go. That’s how most of us do it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.173.78