On 2015-May-29, at 09:24 , Gm [email protected] wrote:
Hi, I have this hash:
hash = { 4049=>[4133, 100], 5814=>[4075, 84], 382543=>[4064, 74], 382544=>[4065,
99], 382545=>[4066, 75] }
I need to sort (DESC) this hash by the second item of array.
Example: 100, 84, 74, 99, 75
How can I solve this problem ? I’m using sort method but can’t work it out.
Thanks.
Well, assuming that you know a Hash isn’t really sortable and you’ll end
up with an Array (of Arrays)…
irb2.2.2> hash = { 4049=>[4133, 100], 5814=>[4075, 84], 382543=>[4064,
74], 382544=>[4065, 99], 382545=>[4066, 75] }
#2.2.2 => {4049=>[4133, 100], 5814=>[4075, 84], 382543=>[4064, 74],
382544=>[4065, 99], 382545=>[4066, 75]}
irb2.2.2> hash.sort_by {|k,v| v[1]}
#2.2.2 => [[382543, [4064, 74]], [382545, [4066, 75]], [5814, [4075,
84]], [382544, [4065, 99]], [4049, [4133, 100]]]
irb2.2.2> hash.sort_by {|k,v| v[1]}.reverse
#2.2.2 => [[4049, [4133, 100]], [382544, [4065, 99]], [5814, [4075,
84]], [382545, [4066, 75]], [382543, [4064, 74]]]
irb2.2.2> hash.sort_by {|k,v| -v[1]}
#2.2.2 => [[4049, [4133, 100]], [382544, [4065, 99]], [5814, [4075,
84]], [382545, [4066, 75]], [382543, [4064, 74]]]
You really want Hash#sort_by
-Rob