我构造了一种方法,该方法合并两个散列,其中两个散列的键值之一相同。该方法如下所示:
def self.hash_merge_on_location(base, additions_arr, location)
base.each_with_index { |b_hash,b_index|
additions_arr.each do |addition|
addition.each_with_index { |a_hash,a_index|
if b_hash[location] == a_hash[location]
base[b_index] = b_hash.merge(a_hash)
end
}
end
}
base
end
所以我的问题是如何使这种方法更好?现在我有基础(哈希数组),additions_arr(哈希数组)和位置(要比较的键)作为参数,并遍历基础数组中的哈希,然后将其与哈希中的每个哈希数组进行比较我的additions_arr。最后,我检查一下我adds_arr中数组中的当前哈希值是否等于基本数组中的哈希值。
一个例子如下:
基本阵列
[{"loan_number" => 10808, "spec_type" => "New"},
{"loan_number" => 10809, "spec_type" => "Old"}]
添加数组
[
[{"loan_number" => 10808, "new_field" => 10},
{"loan_number" => 12383, "new_field" => 19}],
[{"loan_number" => 10809, "new_field" => 11}]
]
现在使用我当前的代码,位置输入为“ loan_number”,hash_merge_on_location的输出为:
输出
[{"loan_number" => 10808, "spec_type" => "New", "new_field" => 10},
{"loan_number" => 10809, "spec_type" => "Old", "new_field" => 11}]
无论如何,现在可以优化我的方法吗?还是我可以做些其他什么来改善它?