Tije Kusnadi
Tije Kusnadi

Reputation: 43

How to merge two array objects in ruby?

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

Answers (4)

Kathryn
Kathryn

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

HardSystem
HardSystem

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

sa77
sa77

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

Sebastián Palma
Sebastián Palma

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

Related Questions