如果我从两个数组开始,例如:
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
如何将此数组合并为一个这样的数组?
arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
答案 0 :(得分:6)
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
p array1 + array2
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
或者这可能是多余的:
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
array3 = [{ID:"3",name:"Duck"}]
p [array1, array2, array3].map(&:first)
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}, {:ID=>"3", :name=>"Duck"}]
答案 1 :(得分:4)
您的问题的其他答案是使用Array#concat
:
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
array1.concat(array2)
# [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
答案 2 :(得分:3)
只需将它们添加到一起:
irb(main):005:0> puts array1+array2
{:ID=>"1", :name=>"Dog"}
{:ID=>"2", :name=>"Cat"}
或者:
irb(main):006:0> p array1+array2
[{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
答案 3 :(得分:0)
您可以使用+
运算符来执行此操作
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
arraymerge = array1 + array2
#=> [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]