Reputation: 43
If I start with two arrays such as:
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
How to merge this array into one array like this?
arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
Upvotes: 4
Views: 8562
Reputation: 1607
Just add them together:
puts array1+array2
{:ID=>"1", :name=>"Dog"}
{:ID=>"2", :name=>"Cat"}
Or:
p array1+array2
[{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
See also: Merge arrays in Ruby/Rails
Upvotes: 3
Reputation: 99
Other answer for your question is to use Array#concat
:
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
array1.concat(array2)
# [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
Upvotes: 5
Reputation: 3603
You can just use +
operator to do that
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
arraymerge = array1 + array2
#=> [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
Upvotes: 0
Reputation: 33420
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
p array1 + array2
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
Or maybe this is superfluous:
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"}]
Upvotes: 10