ruby picture

RCR 270: Add clamp(), modulo(), rand() methods to Range

Submitted by Nick Johnson (Tue Aug 03 14:08:35 UTC 2004)

Abstract

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.

Problem

The Range class does not include all methods which are common operations on ranges.

Proposal

Given than rng is a Range object:

Analysis

Would cause no incompatibility problems; programmers would be free to use or not use these features.

Implementation


    
  1. 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&lt;first
    return last-1 if n&gt;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
ruby picture
Comments Current voting

> ... 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.


Strongly opposed 0
Opposed 1
Neutral 1
In favor 2
Strongly advocate 2
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .