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
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