Home > database >  I want to mege multiple hashes of array into one single hash contaning array of hashes in ruby
I want to mege multiple hashes of array into one single hash contaning array of hashes in ruby

Time:09-23

{products: [{product_number: 2, price: 2}]}
{products: [{product_number: 3, price: 3}]}

output should be:

{products: [{product_number: 2, price: 2}, {product_number: 3, price: 2}]}

CodePudding user response:

You can create a new Hash with previously proposed solution

My thoughts...

Can you set those first two hashes to variables? If so, this solution worked for me...

hash_one = {products: [{product_number: 2, price: 2}]}
hash_two = {products: [{product_number: 3, price: 3}]}
new_hash = Hash.new(0)

new_hash[:products] = [hash_one[:products], hash_two[:products]].flatten

Here's another possible solution...

hash_one = {products: [{product_number: 2, price: 2}]}
hash_two = {products: [{product_number: 3, price: 3}]}
new_hash = Hash.new { |hash, key| hash[key] = []}

hash_one.each do |key, value|
  value.each do |hash|
    new_hash[:products] << hash
  end
end

hash_two.each do |key, value|
  value.each do |hash|
    new_hash[:products] << hash
  end
end

And because I was enjoying this so much, here's one more...

hash_one = {products: [{product_number: 2, price: 2}]}
hash_two = {products: [{product_number: 3, price: 3}]}
new_hash = Hash.new(0)

new_hash[:products] = [hash_one.values[0][0], hash_two.values[0][0]]

Just kidding, I figured out another one...

hash_one = {products: [{product_number: 2, price: 2}]}
hash_two = {products: [{product_number: 3, price: 3}]}
new_hash = Hash.new(0)

new_hash[:products] = [hash_one[:products][0], hash_two[:products][0]]

........

hash_one = {products: [{product_number: 2, price: 2}]}
hash_two = {products: [{product_number: 3, price: 3}]}

new_hash = {products: [hash_one[:products][0], hash_two[:products][0]]}
  •  Tags:  
  • ruby
  • Related