ruby picture

RCR 62: Kernel::rand to accept Range

Submitted by anonymous (Sat Mar 19 22:51:57 UTC 2005)

Abstract

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

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

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

Problem

(RCR imported from old format)

Proposal

Analysis

(RCR imported from old format)

Implementation

(RCR imported from old format)
ruby picture
Comments Current voting

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)

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

then to put a random item from a range:

(0..10).to_a.rand

to get a random line from a file:

File.new("foo.txt", "r").read.split.rand

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.


Strongly opposed 0
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
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 .