首页 > 解决方案 > 如何在哈希数组中找到哈希的最大值

问题描述

在我的数组中,我试图检索具有最大值“value_2”的键,因此在本例中为“B”:

myArray = [
  "A" => {
    "value_1" => 30,
    "value_2" => 240
  },
  "B" => {
    "value_1" => 40,
    "value_2" => 250
  },
  "C" => {
    "value_1" => 18,
    "value_2" => 60
  }
]

myArray.each do |array_hash|
 array_hash.each do |key, value|
  if value["value_2"] == array_hash.values.max
   puts key
  end
 end
end

我得到错误:

"comparison of Hash with Hash failed (ArgumentError)".  

我错过了什么?

标签: ruby

解决方案


虽然等效,但问题中给出的数组通常写成:

arr = [{ "A" => { "value_1" => 30, "value_2" => 240 } },
       { "B" => { "value_1" => 40, "value_2" => 250 } },
       { "C" => { "value_1" => 18, "value_2" =>  60 } }]

我们可以找到所需的密钥,如下所示:

arr.max_by { |h| h.values.first["value_2"] }.keys.first
  #=> "B"

请参阅Enumerable#max_by。步骤是:

g = arr.max_by { |h| h.values.first["value_2"] }
  #=> {"B"=>{"value_1"=>40, "value_2"=>250}} 
a = g.keys
  #=> ["B"] 
a.first
  #=> "B" 

在计算g中,对于

h = arr[0]
  #=> {"A"=>{"value_1"=>30, "value_2"=>240}}

块计算是

a = h.values
  #=> [{"value_1"=>30, "value_2"=>240}] 
b = a.first
  #=> {"value_1"=>30, "value_2"=>240} 
b["value_2"]   
  #=> 240 

假设现在arr如下:

arr << { "D" => { "value_1" => 23, "value_2" => 250 } }
  #=> [{"A"=>{"value_1"=>30, "value_2"=>240}},
  #    {"B"=>{"value_1"=>40, "value_2"=>250}},
  #    {"C"=>{"value_1"=>18, "value_2"=>60}},
  #    {"D"=>{"value_1"=>23, "value_2"=>250}}] 

我们希望返回一个包含"value_2"最大值 ( ["B", "D"]) 的所有键的数组。我们可以如下获得。

max_val = arr.map { |h| h.values.first["value_2"] }.max
  #=> 250
arr.select { |h| h.values.first["value_2"] == max_val }.flat_map(&:keys)
  #=> ["B", "D"]

flat_map(&:keys)是以下的简写:

flat_map { |h| h.keys }

它返回与以下相同的数组:

map { |h| h.keys.first }

请参阅Enumerable#flat_map


推荐阅读