如何在以下条件下合并两个哈希值:
# 1º case
a = {}
b = { "1"=>["c1", "c2"], "2"=>["c2","c3"] }
# merging a and b
# a = { "1"=>["c1", "c2"], "2"=>["c2","c3"] }
# 2º case
a = { "1"=>["c1", "c2"], "2"=>["c2","c3"] }
c = { "1"=>["c1", "c3"], "3"=>["c5"] }
# merging a and c
# a = { "1"=>["c1", "c2", "c3"], "2"=>["c2","c3"], "3"=>["c5"] }
到目前为止我得到了什么:
对于数组,我知道可以与运算符“|”合并
a = ["c0", "c1"], b = ["c1", "c2"]
a = a | b
# a = ["c0", "c1", "c2"]
但是哈希不起作用:
a.merge(b){ |key, oldval, newval| oldval | newval }
# returns whatever was in the first place for the Hash a
S.O中有答案(实际上其中一个使用上面的相同示例),但我无法使其工作(我也尝试与非空哈希合并)。我知道我可以在循环中打开等等......但我正在寻找“红宝石”的方式。
提前致谢。