Jinx
Jinx

Reputation: 43

Merge two hash arrays into one without changing Key value pairs in Ruby

Hi I have two hash arrays as follows

A = [{"name" => "rihan"}, {"name" => "gihan"}, {"name" => "mihan"}]
B = [{"value" => "true"}, {"value" => "true"}, {"value" => "true"}]

how to merge them into single hash array as [{"name" => "rihan", "value" => true"]

As I need to verify them against the pipe delimited cucumber table converted in hashes e.g |name|value |rihan|true| |gihan|true|

For cucumber table I am using below function to convert it into hashes

def create_hash_from_data_table table
 table.hashes.each do |hash| ; @table_hash = hash ; end
 return @table_hash
end

And for actual JSON response I am extracting it using recursive function to above two hash arrays [A] and [B] but I am not sure how to merge them to compare with the cucumber data without overwriting or changing the duplicate values in A[] and B[].

I tried merge and recursive merge option e.g. array1 = array2.merge(array1)

Kindly assist as merge method throws undefined method error

Upvotes: 1

Views: 200

Answers (2)

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

Your question is still very confusing. I am assuming that you have this input:

a = [{"name" => "rihan"}, {"name" => "gihan"}, {"name" => "mihan"}]
b = [{"value" => 1}, {"value" => 2}, {"value" => 3}]

And you desire this output:

[{"name"=>"rihan", "value"=>1},
 {"name"=>"gihan", "value"=>2},
 {"name"=>"mihan", "value"=>3}]

Which can be achieved with:

a.zip(b).map { |ar| ar.inject(:merge) }

Or in this specific case (where the arrays after zipping are always 2-element):

a.zip(b).map { |x,y| x.merge(y) }

As

a.zip(b) #=> [[{"name"=>"rihan"}, {"value"=>1}], [{"name"=>"gihan"}, {"value"=>2}], [{"name"=>"mihan"}, {"value"=>3}]]

And then each element of the array is mapped by merging all of its elements.

Or a bit more explicit version, with a simple loop:

a.size.times.with_object([]) do |i, output|
  output << a[i].merge(b[i])
end

Upvotes: 3

iGian
iGian

Reputation: 11193

Other option, pairing elements from each array by index:

a.map.with_index { |h, i| h.merge(b[i]) }

a #=> [{"name"=>"rihan", :value=>"true"}, {"name"=>"gihan", :value=>"true"}, {"name"=>"mihan", :value=>"true"}]

Upvotes: 1

Related Questions