Search code examples
rubysortinghashruby-on-rails-5

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 i.e., 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

Solution

  • 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.