Is there any quick way to get a (random) permutation of a given hash? For example with arrays I can use the sample method as in
ruby-1.9.2-p180 :031 > a = (1..5).to_a
=> [1, 2, 3, 4, 5]
ruby-1.9.2-p180 :032 > a.sample(a.length)
=> [3, 5, 1, 2, 4]
For hashes I can use the same method on hash keys and build a new hash with
ruby-1.9.2-p180 :036 > h = { 1 => 'a', 2 => 'b', 3 => 'c' }
=> {1=>"a", 2=>"b", 3=>"c"}
ruby-1.9.2-p180 :037 > h.keys.sample(h.length).inject({}) { |h2, k| h2[k] = h[k]; h2 }
=> {3=>"c", 2=>"b", 1=>"a"}
but this is so ugly. Is there any 'sample' method for hashes which can avoid all that code?
Update As pointed out by @Michael Kohl in comments, this question is meaningful only for ruby 1.9.x. Since in 1.8.x Hash are unordered there is no way to do that.
A slight refinement of mu is too short's answer:
h = Hash[h.to_a.shuffle]
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