How to sort not simple hash (hash of hashes)

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

    I would change the data structure to an array of hashes:

    my_array =
    [
      {:id => 78, :value=>64, :rating=>-155},
      {:id => 84, :value=>90, :rating=>-220},
      {:id => 95, :value=>39, :rating=>-92}
    ]
    

    You can sort this kind of structure easily with

    my_array.sort_by { |record| record[:rating] }
    

    To get the hash-like functionality of fetching a record by id you can define a new method on my_array:

    def my_array.find_by_id(id) 
      self.find { |hash| hash[:id] == id }
    end
    

    so after that you can do

    my_array.find_by_id(id)
    

    instead of

    my_hash[id]
    

提交回复
热议问题