【发布时间】:2018-12-20 19:49:57
【问题描述】:
我有一个更改的父散列,我想确保子散列接受这些更改,但也保留他们以前拥有的密钥并且这些不应该丢失
这些是我拥有的示例哈希
one = {"endpoints"=>["get_route"], "features"=>["channel_selection"], "get_route"=>{"output"=>["total_length", "seca_length"], "options"=>["panama", "abcd"]}}
other = {"endpoints"=>["get_route"], "features"=>["channel_selection"], "get_route"=>{"output"=>["total_length", "seca_length"], "options"=>["panama", "suez", "kiel"]}}
我希望另一个哈希现在看起来像
other = {"endpoints"=>["get_route"], "features"=>["channel_selection"], "get_route"=>{"output"=>["total_length", "seca_length"], "options"=>["panama", "abcd", suez", "kiel"]}}
我尝试了以下代码,但它不起作用
result = propogate_changes(one, other)
def propogate_changes(one, other)
one_keys = one.keys
other_keys = other.keys
combined = Hash.new
unique_keys = one_keys.concat(other_keys).uniq
unique_keys.each do |key|
if(one[key].is_a?(Array)) then
# if(other[key] == nil) then
# combined[key] = one[key]
# else
combined[key] = one[key].concat(other[key]).uniq
# end
else
combined[key] = add_allowance(one[key], other[key])
end
end
return combined
end
当一个键存在但另一个键缺失时,上述代码会失败
我也尝试了merge, deep_merge, reverse_merge,但它们都用一个哈希覆盖了我的另一个哈希,但它们都没有保留原始数据。
对此的任何建议将不胜感激
【问题讨论】:
-
目前还不清楚 - 哪个示例哈希是您称为“父”的哈希,哪个子哈希?另外,您想要的输出是什么样的?
-
想用一个散列更新其他散列。我尝试了合并,deep_merge,但它们都覆盖了现有的散列,这不是我想要的。我想保留旧值并添加缺失值
-
您可以使用 slice 方法从一个哈希中获取其他哈希中的键,并将其与其他类似,
other.merge(one.slice(*other.keys))这是您的答案stackoverflow.com/a/6074412/5934752
标签: ruby-on-rails ruby ruby-on-rails-4