Ruby Tuesday – Ranges

This weeks edition of Ruby Tuesday is about ranges. Ranges are Ruby’s way to create an interval of values.

Ranges take a beginning and ending value, which can be inclusive,

(10..20).to_a
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

or exclusive, specified by using ... instead of ..

(10...20).to_a
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

And creating a “invalid” range, will result in a empty set of values, and not throw an exception.

(20..10).to_a
# []

Ranges can be used not only against integer values, but Dates and Strings as well

(Date.today..(Date.today+10)).to_a
# [#<Date: 2014-11-08 ((2456970j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-09 ((2456971j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-10 ((2456972j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-11 ((2456973j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-12 ((2456974j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-13 ((2456975j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-14 ((2456976j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-15 ((2456977j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-16 ((2456978j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-17 ((2456979j,0s,0n),+0s,2299161j)>,
#  #<Date: 2014-11-18 ((2456980j,0s,0n),+0s,2299161j)>]

('a'..'z').to_a
# ["a", "b", "c", "d", "e", "f", "g", "h",
#  "i", "j", "k", "l", "m", "n", "o", "p",
#  "q", "r", "s", "t", "u", "v", "w", "x",
#  "y", "z"]

In fact Ranges can be created from any type that implements the <=> operator.

Be warned though, just because you can create a Range, doesn’t mean that you can turn every Range into an Array as above.

(1.0..2.0).to_a
TypeError: can't iterate from Float
from (pry):58:in `each'

There is more that you can do with Ranges, such as checking if a value is in the range, or stepping through the values, but some of the methods on Range have requirements that certain methods be declared on the type the range is operating on.

–Proctor

1 thought on “Ruby Tuesday – Ranges

  1. Pingback: Erlang Thursday – lists:seqProctor It | Proctor It

Comments are closed.