How to sort not simple hash (hash of hashes)

前端 未结 3 875
执笔经年
执笔经年 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:56

    There might be a better data structure, but (I'm assuming this is ruby) it's possible to do in Ruby by using the inline sort style to basically tell it how to compare the two. Here's a concrete example:

    my_hash = { 
      55 => {:value=>61, :rating=>-147},
      89 => {:value=>72, :rating=>-175},
      78 => {:value=>64, :rating=>-155},
      84 => {:value=>90, :rating=>-220},
      95 => {:value=>39, :rating=>-92},
      46 => {:value=>97, :rating=>-237},
      52 => {:value=>73, :rating=>-177},
      64 => {:value=>69, :rating=>-167},
      86 => {:value=>68, :rating=>-165},
      53 => {:value=>20, :rating=>-45}
    }
    
    puts "MY HASH"
    my_hash.each do |local|
      puts local
    end
    
    sorted_hash = my_hash.sort  { | leftval, rightval | rightval[1][:rating]<=>leftval[1][:rating] }
    
    puts "SORTED HASH"
    sorted_hash.each do |local|
      puts local
    end
    

提交回复
热议问题