0
A = [
  { :id => 1, :name => 'good', :link => nil },
  { :id => 2, :name => 'bad', :link => nil } 
]

B = [
  { :id => 3, :name => 'good' },
  { :id => 4, :name => 'good' }, 
  { :id => 5, :name => 'bad' } 
]

I need to merge array B into A so that :link in array A includes the entry in array B if :name is the same value in each array.

For example, after processing array A should be:

A = [
  { :id => 1, :name => 'good', :link => [{ :id => 3, :name => 'good' }, { :id => 4, :name => 'good' }] },
  { :id => 2, :name => 'bad', :link => [{ :id => 5, :name => 'bad' }] }
]

thanks.

3
  • is the expected A correct? bad should have link (id=5). Commented Feb 27, 2012 at 13:33
  • hint: don't upload, create new objects (so merge instead of update). Commented Feb 27, 2012 at 13:33
  • @tokland: sorry, you are right. bad should have link (id=5). thanks. Commented Feb 27, 2012 at 15:04

3 Answers 3

3

The short version;

a.each { | item | item[:link] = b.find_all { | x | x[:name] == item[:name] } }

Demo here.

Sign up to request clarification or add additional context in comments.

1 Comment

of course, this only updates existing values in a, it doesn't create new keys from b if they exist in ba but not a.
1

In ruby the constants begin with an uppercase letter, so you should use lowercase letter: A => a, B => b

a.each do |ha|
  b.each do |hb|
    if ha[:name] == hb[:name]
      ha[:link] |= []
      ha[:link] << hb
    end
  end
end

Comments

0

Functional approach:

B_grouped = B.group_by { |h| h[:name]  }
A2 = A.map { |h| h.merge(:link => B_grouped[h[:name]]) }
#=> [{:link=>[{:name=>"good", :id=>3}, {:name=>"good", :id=>4}], :name=>"good", :id=>1},
#    {:link=>[{:name=>"bad", :id=>5}], :name=>"bad", :id=>2}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.