简体   繁体   English

将两个哈希数组合并为一个而不更改Ruby中的键值对

[英]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"] 如何将它们合并为单个哈希数组,如[{“ name” =>“ rihan”,“ value” => true“]

As I need to verify them against the pipe delimited cucumber table converted in hashes eg |name|value |rihan|true| 因为我需要对照以散列符(例如| name | value | rihan | true |)转换的管道分隔黄瓜表来验证它们 |gihan|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[]. 对于实际的JSON响应,我正在使用递归函数将其提取到两个以上的哈希数组[A]和[B]中,但是我不确定如何合并它们以与黄瓜数据进行比较,而不会覆盖或更改A []中的重复值和B []。

I tried merge and recursive merge option eg array1 = array2.merge(array1) 我尝试了合并和递归合并选项,例如array1 = array2.merge(array1)

Kindly assist as merge method throws undefined method error 请协助,因为合并方法会引发未定义的方法错误

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): 或在这种特定情况下(压缩后的数组始终为2元素):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM