Ruby Ranges

From Techotopia
Revision as of 19:04, 20 November 2007 by Neil (Talk | contribs) (New page: Ruby Ranges allow data to be represented in the form of a range (in other words a data set with start and end values and a logical sequence of values in between). The values in a range can...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Ruby Ranges allow data to be represented in the form of a range (in other words a data set with start and end values and a logical sequence of values in between). The values in a range can be numbers, characters, strings or objects. In the chapter we will look at the three types of range supported by Ruby, sequences, conditions and intervals.

Ruby Sequence Ranges

Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value and a range of values in between.

Two operators are available for creating such ranges, the inclusive two-dot (..) operator and the exclusive three-dot operator (...). The inclusive operator includes both the begin and end values in the range. The exclusive range operator excludes the end value from the sequence. For example:

1..10    # Creates a range from 1 to 10 inclusive
1...10   # Creates a range from 1 to 9

A range may be converted to a list using the Ruby to_a method. For example:

(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(1...10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

As mentioned previously, ranges are not restricted to numerical values. We can also create a character based range:

('a'..'l').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]

Also, we can create range based on string values:

('cab'..'car').to_a
=> ["cab", "cac", "cad", "cae", "caf", "cag", "cah", "cai", "caj", "cak", "cal", "cam", "can", "cao", "cap", "caq", "car"]

Range values may also be objects. The only requirements for placing an object in a range is that the object provides a mechanism for returning the next object in the sequence via succ and it must be possible to compare the objects using the <=> operator.

Using Range Methods

Given the object-oriented nature of Ruby it should come as no surprise to you that a range is actually an object. As such, there are a number of methods of the Range class which can be accessed interrogate and manipulate a range object.

words = 'cab'..'car'

words.min         # get lowest value in range
=> "cab"

words.max         # get highest value in range
=> "car"

words.include?('can') # check to see if a value exists in the range
=> true

words.reject {|subrange| subrange < 'cal'} # reject values below a specified range value
=> ["cal", "cam", "can", "cao", "cap", "caq", "car"]