我想合并两个数组array1和array2与列值匹配。两个阵列之间的绘图ID可能匹配也可能不匹配。匹配列是array1中的Plot ID和array2中的Plotting ID。
占主导地位……
array1 = [{"Date" => "2019-01-01", "Plot ID" => 234}, {"Date" => "2019-01-01", "Plot ID" => 235}, {"Date" => "2019-01-01", "Plot ID" => 236}, {"Date" => "2019-01-01", "Plot ID" => 237}, {"Date" => "2019-01-01", "Plot ID" => 238}, {"Date" => "2019-01-01", "Plot ID" => 239}, {"Date" => "2019-01-01", "Plot ID" => 240}, {"Date" => "2019-01-01", "Plot ID" => 241}] array2 = [{"Date" => "2019-01-01", "Plotting ID" => 234, "size"=> 20, "visit" => 10, "price" => 103}, {"Date" => "2019-01-01", "Plotting ID" => 500, "size"=> 40, "visit" => 22, "price" => 233}, {"Date" => "2019-01-01", "Plotting ID" => 236, "size"=> 25, "visit" => 34, "price" => 423}, {"Date" => "2019-01-01", "Plotting ID" => 600, "size"=> 79, "visit" => 55, "price" => 234}] grouped = (array2 + array1).group_by { |h| h["Plot ID"] || h["Plotting ID"] } merged = grouped.values.map { |a| a.inject(:merge) } # and in case you want exact formatting: template = { "Date" => nil, "Plot ID" => nil, "size"=> 0, "visit" => 0, "price" => 0 } normalized = merged.each { |h| template.merge(h).slice(*template.keys) }
您可以看到每行代码如何对数据进行有意义且独立的转换。我发现这样的代码更容易在调试器中单步执行。
学习组合内置的 Enumerable 和 Hash 方法并大大简化您的代码!
Enumerable
Hash