Submitted by Nick Johnson (Tue Aug 03 14:08:35 UTC 2004)
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.
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
Comments | Current voting | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
RCRchive copyright © David Alan Black, 2003-2005.
Powered by .
> ... a Range object is not merely a duple of integers
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
Can you post some sample code that uses these methods?
-- Paul Brannan
Your Range#rand implementation is rather wrong, it assumes Range#min is 0. (4..7).rand would not return a random number between 4 and 7, but between 0 and 3, assuming there was a Range#length.