04 Jul, 2009, Runter wrote in the 1st comment:
Votes: 0
This lets you pass enumerations and arrays to rand to get a balanced selection.
Also an Array extension for a rand function.

### Decided to give array an extension so you can do [1,2,3].rand to grab a random element of an array.
class Array
def rand
self[Kernel.rand(self.length)]
end
end

### make o_rand an alias of our original rand
alias o_rand rand

### redefine rand to make a call to o_rand with a wrapper.
def rand a1=nil, a2=nil
if !a1.kind_of?(Enumerable) and a2 == nil
o_rand(a1)
elsif a1.kind_of?(Enumerable)
as_array = a1.to_a
as_array[o_rand(as_array.length)]
elsif a1 != nil
a1 + o_rand(a2)
end
end


1000.times do
rand 1..100
end


1000 iterations as usual said:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
38.46 0.05 0.05 1000 0.05 0.12 Object#rand
23.08 0.08 0.03 1000 0.03 0.03 Range#each
15.38 0.10 0.02 1000 0.02 0.02 Array#[]
7.69 0.11 0.01 2000 0.01 0.01 Kernel.kind_of?
7.69 0.12 0.01 1000 0.01 0.04 Enumerable.to_a
7.69 0.13 0.01 1 10.00 130.00 Integer#times
0.0/1