This is a legacy RCR. If this is your RCR, please resubmit it using the new format and process.
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.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. :~)
Back to RCRchive.
RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog
Any thoughts on randomly removing an element from an array vs randomly selecting?