Comment on this RCR (edit wiki page) | RCRchive home

RCR 62: Kernel::rand to accept Range

submitted by anonymous on 2002-02-11 08:27:03


This is a legacy RCR. If this is your RCR, please resubmit it using the new format and process.


I would like rand() to be able to take a Range as a parameter:

rand(20..30) #=> random number between 20 and 30.

rand(40...50) #=> random number between 40 and 49.


Vote for this RCR

Strongly opposed [0]
Opposed [0]
Neutral [1]
In favor [12]
Strongly advocate [10]

Change the status of this RCR to:

accepted

rejected

withdrawn


Add comments here

Another approach (, 2002-02-11 10:33:15)

Range#rand and Array#rand would also be useful:

  (45..96).rand<br>

  [23, 67, 34, 68].rand<br>

Any thoughts on randomly removing an element from an array vs randomly selecting?

That might work (, 2002-02-11 10:54:58)

<tt> class Array
  def rand() at super(size)<br>
  end<br>
end </tt>

then to put a random item from a range:

<tt> (0..10).to_a.rand </tt>

to get a random line from a file:

<tt> File.new("foo.txt", "r").read.split.rand </tt>

One danger of this is that Range.to_a might return a ridiculous number of elements.

Interesting idea (cout, 2002-02-12 12:01:08)

I'm not convinced that it makes sense to make this an instance method. Here's an implentation that overrides rand() to work on any container that has size() and each() defined:

module Kernel
  orig_rand = method(:rand)
  define_method(:rand) do |x|
    if x.respond_to?(:each) and x.respond_to?(:size) then
      raise ArgumentError, "Invalid container size" if x.size == 0
      n = rand(x.size); j = 0
      for y in x do
        break if j == n
        j += 1
      end
      y # return
    else
      orig_rand.call(x) # return
    end
  end
end
p rand(10) p rand(2..20) p rand([100, 200, 300, 400]) p rand({1=>2, 2=>3, 3=>4, 4=>5})

Two paramaters.... (seanoc, 2002-04-22 19:10:37)

Kernel#rand(min = 0, max = 1, int = false)

Seems excessive to need a range object to specify a lower and upper bound. It'd be nice to specify whether or not it should be an int too. ;~) More sugar. :~)

Re: Interesting idea (, 2003-07-03 21:53:01)

I really like that. You could also optimize it so that if an object responds to at, (Array or String), it wouldn't iterate through them all.

Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog