The Range object is <i>under-interpreted</i> as a range. As a Range object is not merely a duple of integers, there is room for more methods which take advantage of its meaning.
The Range class does not include all methods which are common operations on ranges.
# in addition to what is already there
class Range
# returns a value within the range
# will return lowest or highest
# value if n is out of range in the
# lower or upper directions
# (respectively)
def clamp(n)
return first if n<first
return last-1 if n>last-1 && exclude_end?
return last if n>last
n
end
# maps n to a value in the range.
# this comes up in many algorithms.
def modulo(n)
n.modulo(length) + first
end
# choose a random member of this range
def rand
modulo Kernel::rand(length)
end
end
Actually it doesn't specifically involve integers at all. 'a'..'z' is a Range object, as is 1.345..2.789, so "last - 1" won't always mean anything. Also, there's no Range#length method, so your #modulo and #rand methods won't work.
I guess it would be possible to limit these methods to certain flavors of Range. #to_a already does that (you can't do #to_a on ranges of floats, because you can't iterate over the range).
-- David Black
-- Paul Brannan
Back to RCRchive.
RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog