【问题标题】:How do I sort a hash with the highest specific value?如何对具有最高特定值的哈希进行排序?
【发布时间】:2014-06-26 21:18:26
【问题描述】:

我在一个名为 elem 的数组中有哈希值,我必须获得具有最高“计数”值的“类型”键。

我知道枚举器是一个很棒的知识,但我不太了解它们。

elem = [{"type"=>"dododo", "count"=>0, "name"=>"dododo's", "tip"=>"dododo's Level"},
  {"type"=>"dadada", "count"=>1203, "name"=>"dadada's", "tip"=>"dadada's Degree"},
  {"type"=>"dedede", "count"=>717, "name"=>"dedede's", "tip"=>"dedede's Degree"},
  {"type"=>"dididi", "count"=>6, "name"=>"dididi's", "tip"=>"dididi or Professional Degree"}]

我正在尝试这个:

elem.each do |i|
  i.each_with_index do |k,v|
    puts v["count"]
  end
end

但我知道我错过了一些步骤。

我知道这种“策略”相当常见,而且很重要。

【问题讨论】:

  • 您可能想要编辑标题,作为记录,因为您没有排序,更不用说对哈希进行排序了。可能是这样的,“如何从哈希数组中提取特定的哈希值?

标签: ruby arrays sorting hash enums


【解决方案1】:

一种方法是使用Enumerable#max_by

elem = [
  {"type"=>"dododo", "count"=>0, "name"=>"dododo's", "tip"=>"dododo's Level"},
  {"type"=>"dadada", "count"=>1203, "name"=>"dadada's", "tip"=>"dadada's Degree"},
  {"type"=>"dedede", "count"=>717, "name"=>"dedede's", "tip"=>"dedede's Degree"},
  {"type"=>"dididi", "count"=>6, "name"=>"dididi's", "tip"=>"dididi or Professional Degree"}
]

max_elem = elem.max_by {|e| e['count']}
puts max_elem['type']
# returns dadada

【讨论】:

  • 非常感谢@infused!感谢您的快速响应:)
猜你喜欢
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 2011-02-02
  • 2023-04-01
相关资源
最近更新 更多