How to sort not simple hash (hash of hashes)

前端 未结 3 863
执笔经年
执笔经年 2021-02-04 20:20

I have a Hash like this

{ 55 => {:value=>61, :rating=>-147},
  89 => {:value=>72, :rating=>-175},
  78 => {:value=>64, :rating=>-155},         


        
3条回答
  •  醉话见心
    2021-02-04 20:36

    Hashes in Ruby can't be sorted (at least not before 1.9)

    This means that looping through a Hash won't necessarily yield the information in the right order for you. However, it's trivial to loop through Hashed data in a particular order by converting it to an Array first, and in fact calling the sort methods on a Hash will convert it into an Array for you:

    >> { :a => 4, :b => 12, :c => 3, :d => 8 }.sort_by { |key, value| value }
    => [[:c, 3], [:a, 4], [:d, 8], [:b, 12]]
    

    So in your case:

    hsh.sort_by {|key, ratings| ratings[:rating] }
    

提交回复
热议问题