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
Back to RCRchive.
RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog