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?
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.
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})
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. :~)
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.
Another approach (, 2002-02-11 10:33:15)
Any thoughts on randomly removing an element from an array vs randomly selecting?
That might work (, 2002-02-11 10:54:58)
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:
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)