Ranges

In Ruby, a Range is a class that represents a set of values defined by a starting value and an ending value. Typically a range is defined using integers, but it may also be defined using other ordered values such as floating-point numbers or characters. Values can be negative, though you should be careful that your starting value is lower than your ending value!

Here are a few examples:

ranges.rb

a = (1..10)
b = (-10..-1)
c = (-10..10)
d = ('a'..'z')

You can also specify ranges using three dots instead of two; this creates a range that omits the final value:

d = ('a'..'z')         # this two-dot range = 'a'..'z'
e = ('a'...'z')        # this three-dot range = 'a'..'y'

You can create an array of the values defined by a range using the to_a method, like this:

(1..10).to_a

Note that to_a is not defined for floating-point numbers for the simple reason that the number of possible values between two floating-point numbers is not finite.

Ranges of Strings

You can even create ranges of strings—though you would need to take great care in so doing because you might end up with more than you bargain for. For example, see whether you can figure out which values are specified by this range:

str_range.rb

str_range = ('abc'..'def')

At first sight, the range from 'abc' to 'def' might not look like much. In fact, this defines a range of no less than 2,110 values! They are ordered like this: abc, abd, abe, and so on, until the end of the as; then you start on the bs: baa, bab, bac, and so on. Suffice to say that ranges of this sort are probably rather a rare requirement and are best used with extreme caution or not at all.

Iterating with a Range

You may use a range to iterate from a start value to an end value. For example, here is one way of printing all the numbers from 1 to 10:

for_to.rb

for i in (1..10) do
    puts( i )
end
..................Content has been hidden....................

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