将哈希值合并到数组中

时间:2017-06-01 17:07:02

标签: arrays ruby hash

我是Ruby的新手。我有两个哈希数组

arr1 = [{"one"=> {"1"=> "a", "2" => "b"}, "two" => {"3" => "n", "5" => "h", "7" => "k"}]
arr2 = [{"one"=> {"8"=> "f", "11" => "r"}, "two" => {"7" => "o", "6" => "b", "14" => "b"}]

我希望有一个这样的数组:

arr3 = [{
"one"=> {"1"=> "a", "2" => "b", "8"=> "f", "11" => "r"}, 
"two" => {3" => 'n", "5" => "h", "7" => "k", 7" => 'o", "6" => "b", "14" => "b"}
]

所以我想通过键合并哈希和#34;添加"他们的价值观有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

arr1 = [{"one"=>{"1"=>"a",  "2"=>"b"}, "two"=>{"3"=>"n", "5"=>"h",  "7"=>"k"}}]
arr2 = [{"one"=>{"8"=>"f", "11"=>"r"}, "two"=>{"7"=>"o", "6"=>"b", "14"=>"b"}}]

(arr1+arr2).each_with_object({}) { |g,h| h.update(g) { |_,o,n| o.merge(n) } }
  # => {"one"=>{"1"=>"a", "2"=>"b", "8"=>"f", "11"=>"r"},
  #     "two"=>{"3"=>"n", "5"=>"h", "7"=>"o", "6"=>"b", "14"=>"b"}}

这使用Hash#update(aka merge!)的形式,当两个哈希值合并时,使用块({ |_k,o,n| o.merge(n) })来确定键_k的值那把钥匙。 (_中的_k告诉读者块块变量未在块计算中使用。)onh中该键的值分别和g

对于等于k"one"的每个键"two",如果arr1.first[k]arr2.first[k]的值(哈希值)具有公共密钥{{1 }},合并操作将导致ll的值被arr1l的值覆盖。例如,如果arr2arr1.first["one"] #=> {"1"=>"a", "2"=>"b"},合并将返回arr2.first["one"] #=> {"8"=>"f", "2"=>"r"}

尽管{"1"=>"a", "2"=>"r", "8"=>"f"}arr1每个都包含一个元素(哈希),但是当数组包含多个哈希值时,以及当有两个以上的数组时,上面的代码工作正常。如果数组总是包含一个哈希,那么数组没有用处,我们可能只引用哈希:

arr2

并将h1 = {"one"=>{"1"=>"a", "2"=>"b"}, "two"=>{"3"=>"n", "5"=>"h", "7"=>"k"}} h2 = {"one"=>{"8"=>"f", "11"=>"r"}, "two"=>{"7"=>"o", "6"=>"b", "14"=>"b"}} 替换为arr1+arr2

答案 1 :(得分:0)

也许不是最优雅的,但这有效:

arr1 = [{"one"=>{"1"=>"a",  "2"=>"b"}, "two"=>{"3"=>"n", "5"=>"h",  "7"=>"k"}}]
arr2 = [{"one"=>{"8"=>"f", "11"=>"r"}, "two"=>{"7"=>"o", "6"=>"b", "14"=>"b"}}]
arr3 = []
arr1[0].each_key{|k| arr3<< {k => arr1[0][k].merge(arr2[0][k])}}
arr3

如果您不知道原始数组将包含多少哈希值,只需将arr1[0].each_key替换为arr1.each_index{|i| arr1[i].each_key,并将0替换为合并中的i