如何在Ruby中合并哈希(键和内容)数组的内容

时间:2009-11-05 10:23:46

标签: ruby arrays hash

myArray = [{"papers"=>[[1,2,3],[1,3,2]], "value"=>"1"},
           {"papers"=>[[2,1,3],[2,3,1]], "value"=>"1"}, 
           {"papers"=>[[1,2,3],[1,3,2]], "value"=>"0.5"}]

我需要根据每个包含的数组的“值”合并内容,这样我最终会得到这样的结果:

myArray = [{"papers"=>[[1,2,3],[1,3,2],[2,1,3],[2,3,1]], "value"=>"1"}, 
           {"papers"=>[[1,2,3],[1,3,2]], "value"=>"0.5"}]

我将如何以Ruby方式执行此操作?

我想过迭代数组,并根据值创建一个新数组,但我一直在试图找出如何定义被复制的内容。

1 个答案:

答案 0 :(得分:4)

>> myArray = [{"papers"=>[[1,2,3],[1,3,2]], "value"=>"1"},
?>            {"papers"=>[[2,1,3],[2,3,1]], "value"=>"1"}, 
?>            {"papers"=>[[1,2,3],[1,3,2]], "value"=>"0.5"}]

>> hash = Hash.new {|h,k| h[k] = []}

>> myArray.each {|entry| hash[entry['value']] += entry['papers']}

>> hash
=> {"1"=>[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]], "0.5"=>[[1, 2, 3], [1, 3, 2]]}

>> hash.map {|k,v| {"value" => k, "papers" => v}}
=> [{"value"=>"1", "papers"=>[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]]}, {"value"=>"0.5", "papers"=>[[1, 2, 3], [1, 3, 2]]}]