简体   繁体   中英

How to sort a hash with a value inside it

I've a hash

H = { abc: [1,1,2], def: [0,1,1], efg: [3,4,7] }

How to sort descending these with the last index of the array ie, I need the hash to be like this H = { efg: [3,4,7], abc: [1,1,2], def: [0,1,1]}

H.values[2].sort

You can convert it into an array then back into a hash:

x = {a: [1,2,3], c: [7,8,9], b: [4,5,6]}
x.sort_by { |k,v| v.last }.reverse.to_h
# => {:c=>[7, 8, 9], :b=>[4, 5, 6], :a=>[1, 2, 3]}

sort_by turns it into array of tuples:

x.sort_by { |k,v| v.last }
# => [[:a, [1, 2, 3]], [:b, [4, 5, 6]], [:c, [7, 8, 9]]]

Of course you can call .reverse to get descending order

and you can call .to_h on this data structure to make a hash again.

Although, it's not normal to think of hashes as ordered structures, I think they do actually preserve order but usually if you are working with ordered data you will keep it as an array. I would question why you need to use an ordered hash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM