Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中从关联数组中查找最高值_Ruby_Hash - Fatal编程技术网

在Ruby中从关联数组中查找最高值

在Ruby中从关联数组中查找最高值,ruby,hash,Ruby,Hash,我有一个复杂的散列,看起来像这样 @hash = {1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[], 10=>[], 11=>[], 12=>[[{"value"=>1.58, "title"=>"sun", "quantity" => 2}], [{"value"=>1.99, "title"=>"sophia",

我有一个复杂的散列,看起来像这样

 @hash =  {1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[], 10=>[], 11=>[], 12=>[[{"value"=>1.58, "title"=>"sun", "quantity" => 2}], [{"value"=>1.99, "title"=>"sophia", "quantity" => 5}], [{"value"=>6.30, "title"=>"roam", "quantity" => 15}], [{"value"=>3.981, "title"=>"jia, "quantity" => 4"}], 13 => [], 14 => [], 15 => []}
现在我想提取最高值以及相关的标题和数量。指数始终为15

例如,输出应该是

@hash = { value => 6.30, title => "roam", quantity => 15 }
我在搜索一些发现了这个,但是没有成功 参考链接


帮助感谢

如果您对元素的索引不感兴趣,可以将值展平并找到最大值:

@hash =  {
  1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[],
  10=>[], 11=>[], 12=>[
    [{"value"=>1.58, "title"=>"sun", "quantity" => 2}],
    [{"value"=>1.99, "title"=>"sophia", "quantity" => 5}],
    [{"value"=>6.30, "title"=>"roam", "quantity" => 15}],
    [{"value"=>3.981, "title"=>"jia", "quantity" => "4"}]
  ],
  13 => [], 14 => [], 15 => []
}

@hash.values.flatten.max_by { |h| h["value"] }
#=> {"value"=>6.3, "title"=>"roam", "quantity"=>15}

这个散列不是有效的Ruby。可能是这样:
@hash={1=>[],2=>[],3=>[],4=>[],5=>[],6=>[],7=>[],8=>[],9=>[],10=>[],11=>[],12=>[{“value”=>1.58,“title”=>“sun”,“quantity”=>2}],{“value”=>1.99,“title”=>“sophia”,“quantity”=>5}],{“value”=>6.30,“title”=>“roam”,“quantity”=>15”,“quantity”=>3”=>=>4}]],13=>[],14=>[],15=>[]}
您的哈希值有效吗?谢谢,但是我不能删除元素的索引..还有其他方法可以解决吗this@JNI_OnLoad您的预期输出是什么?我只需要具有关联标题和数量的最高值…我在过滤数据1天后创建了此哈希,我希望现在您明白我为什么需要元素…
6.3
是最高值,
“roam”
是关联的标题,
15
是关联的数量。请编辑您的问题以澄清您的要求。是的,谢谢更新。。。