I am trying to split an array of names into multiple arrays in random order each time it is run. I know how to split them with:
name_array = ["bob","john","rob","nate","nelly","michael"]
array = name_array.each_slice(2).to_a
=> [["bob", "john"], ["rob", "nate"], ["nelly", "michael"]]
But, what if I want it to spit them out in random order each time?
Before do the same thing, shuffle the array. (Array#shuffle
)
name_array.shuffle.each_slice(2).to_a
# => [["nelly", "nate"], ["rob", "bob"], ["michael", "john"]]
or, shuffle afterward according to your need:
name_array.each_slice(2).to_a.shuffle
# => [["nelly", "michael"], ["rob", "nate"], ["bob", "john"]]
If you know the size of the original array, then:
name_array.sample 6
Array#sample shortens your method chain over the use of Array#shuffle. If you don't want to hard-code the size of the sample, you can introspect the array for its size at run-time. For example:
name_array.sample(name_array.size)
If you don't need to insist that a given name appears only once in your result set, then you might also consider Array#permutation:
name_array.permutation(2).to_a.sample(name_array.size)
The results will vary, but here's a pretty-printed sample of the results you might expect from this approach:
[["michael", "rob"],
["bob", "nelly"],
["rob", "bob"],
["michael", "nelly"],
["john", "michael"],
["john", "rob"]]
Shuffle the array first, then slice:
["bob","john","rob","nate","nelly","michael"].shuffle.each_slice(2).to_a
#=> [["nelly", "nate"], ["rob", "michael"], ["john", "bob"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With