Ruby Hash: ordering a hash based on values ​​(which are arrays of values)

I want to return a new hash based on reordering the values ​​in the hash. The values ​​themselves are ints arrays.

For instance:

hsh = {"c2" => [44,2], "c1" => [11,33], "c9" => [23,7]}

I would like to be able to return a reordered hash based on a value of 0 or 1 in the values.

Any help here is much appreciated - thanks everyone.

+3
source share
1 answer

From the nature of the question, I assume this is for ruby ​​1.9.

p Hash[hsh.sort_by{|k, v| v[0]}]
# => {"c1"=>[11, 33], "c9"=>[23, 7], "c2"=>[44, 2]}

p Hash[hsh.sort_by{|k, v| v[1]}]
# => {"c2"=>[44, 2], "c9"=>[23, 7], "c1"=>[11, 33]}
+5
source

All Articles