Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash permutation

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.

like image 983
Fabio Avatar asked Dec 12 '22 09:12

Fabio


1 Answers

A slight refinement of mu is too short's answer:

h = Hash[h.to_a.shuffle]
like image 72
steenslag Avatar answered Dec 26 '22 19:12

steenslag