Editing Topic: RCR270 Project: RCR | RCRchive home

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

submitted by Nick Johnson on Tue Aug 03 2004 10:39:35 AM -0700

Status: pending


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

# 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