How to combine two array objects in ruby?

If I start with two arrays like:

array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]

      

How can I combine this array into one array?

arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]

      

+3


source to share


4 answers


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 unnecessary:



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"}]

      

+5


source


The perfect answer to your question:

array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
arraymerge = array1.concat(array2)

# Output: [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]

      



Please vote +1 if u like my answer!

+4


source


Just add them together:

irb(main):005:0> puts array1+array2
{:ID=>"1", :name=>"Dog"}
{:ID=>"2", :name=>"Cat"}

      

Or:

irb(main):006:0> p array1+array2
[{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]

      

See also: Concatenate Arrays in Ruby / Rails

+3


source


You can just use the operator +

for this

array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]

arraymerge = array1 + array2
#=> [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]

      

0


source







All Articles