4

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"}]
1
  • 1
    array1 + array2 #=> [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}] Commented Jun 15, 2017 at 0:26

4 Answers 4

10
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"}]
Sign up to request clarification or add additional context in comments.

2 Comments

can we remove ":" ?
No @TijeKusnadi, that wouldn't work, that's they way to call to_proc on the object, is equivalent to write .map{|e| e.first}, you can choose what to use.
5

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

Comments

3

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

3 Comments

arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
i want the array symbol still there , how do i do that?
It's still an array. puts prints it a little differently than p does.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.