Array#random ?

J

John W. Long

I've often thought it would be nice to have a "random" method for Array.
Has this ever been considered for part of the core? Something like:

class Array
def random
self[rand(size)] if size > 0
end
def pop_random
slice!(rand(size)) if size > 0
end
def randomize
dup.randomize!
end
def randomize!
a = []
a << pop_random until size == 0
concat(a)
end
end

puts [1,2,3].random

a = [1,2,3,4,5,6]
6.times { puts a.pop_random }
puts a.inspect

a = %w{a b c d e f}
b = a.randomize
puts b.inspect
puts a.inspect
a.randomize!
puts a.inspect

Purely a convenience method I know, but would usage be common enough to
justify an RCR? I like the above syntax primarily because it allows you
to do things like:

case [1,2,3].random
when 1
puts "Hi"
when 2
puts "Hello, hello!"
when 3
puts "Howdy"
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,150
Messages
2,570,853
Members
47,394
Latest member
Olekdev

Latest Threads

Top