如何排序不简单的散列(哈希散列) [英] How to sort not simple hash (hash of hashes)

查看:92
本文介绍了如何排序不简单的散列(哈希散列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的哈希

I have a Hash like this

{ 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}
}

我如何通过 :评分 对其进行排序?或者也许我应该使用一些不同的结构?

How can i sort it by :rating? Or maybe i should use some different structure?

推荐答案

我会将数据结构更改为哈希数组:

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] }

为了获得通过id获取记录的哈希式功能,您可以在my_array上定义一个新的方法:

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

/ p>

so after that you can do

my_array.find_by_id(id)

而不是

instead of

my_hash[id]

这篇关于如何排序不简单的散列(哈希散列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆