A Range
represents an interval—a set of values with a start and an end. Ranges may be constructed using the s..
e and s...
e literals, or with Range.new
. Ranges constructed using ..
run from the start to the end inclusively. Those created using ...
exclude the end value. When used as an iterator, ranges return each value in the sequence.
(-1..-5).to_a → []
(-5..-1).to_a → [-5, -4, -3, -2, -1]
('a'..'e').to_a → ["a", "b", "c", "d", "e"]
('a'...'e').to_a → ["a", "b", "c", "d"]
Ranges can be constructed using objects of any type, as long as the objects can be compared using their <=>
operator and they support the succ
method to return the next object in sequence.
class Xs # represent a string of 'x's
include Comparable
attr :length
def initialize(n)
@length = n
end
def succ
Xs.new(@length + 1)
end
def <=>(other)
raise TypeError unless other.kind_of? Xs
@length <=> other.length
end
def inspect
'x' * @length
end
end
r = Xs.new(3)..Xs.new(6) → xxx..xxxxxx
r.to_a → [xxx, xxxx, xxxxx, xxxxxx]
r.member?(Xs.new(5)) → true
Enumerable
collect
, detect
, each_with_index
, entries
, find
, find_all
, grep
, include?
, map
, max
, member?
, min
, reject
, select
, sort
, to_a
=false
) → aRangefalse
, the range will include the end object; otherwise, it will be excluded.true
or false
true
if anObject is an element of rng,
false
otherwise. Conveniently, ===
is the comparison
operator used by case
statements.
case 79
when 1..50 then print "low\n"
when 51..75 then print "medium\n"
when 76..100 then print "high\n"
end
produces:
high
(10..15).each do |n|
print n, ' '
end
produces:
10 11 12 13 14 15
Range#length
.
(1..10).end → 10
(1...10).end → 10
true
or false
true
if rng excludes its end value.
Range#end
.
(1..10).length → 10
(1...10).length → 9
Range#length
.Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.