Ruby合并两个哈希与选择性覆盖

时间:2014-03-04 13:14:03

标签: ruby hash merge

我有两个不同的哈希,使用相同的键:

a = {"word"=>"phileas", "character"=>1, "location"=>0, "adjective"=>0, "noun"=>1}
b = {"word"=>"phileas", "character"=>0, "location"=>1, "adjective"=>1, "noun"=>0}

我想将这两个哈希合并为以下格式:

a = {"word"=>"phileas", "character"=>1, "location"=>1, "adjective"=>1, "noun"=>1}

我试过这段代码:

a.update(b){|key,oldval,newval| !oldval.is_a?(String)  ? oldval | newval :  oldval+newval}

但它给了我以下内容:

{"word"=>"phileasphileas", "character"=>0, "location"=>1, "adjective"=>1, "noun"=>0}

问题是我无法在String值上创建条件。合并时,它也会合并String值。我希望String值保持不变并合并其余部分。如果其他值大于0,我希望保留该值。您可以将这些值视为布尔值或标记。

1 个答案:

答案 0 :(得分:2)

p a.merge(b) { |k,v1,v2| v1.is_a?(String) ? v1 : v1 | v2 }
# => {"word"=>"phileas", "character"=>1, "location"=>1, "adjective"=>1, "noun"=>1}

检查您的密钥是否为Fixnum类型实际上更有意义,因此您确定它支持逻辑OR运算符,并保持其他值不变:

p a.merge(b) { |k,v1,v2| v1.is_a?(Fixnum) ? v1 | v2 : v1 }
# => {"word"=>"phileas", "character"=>1, "location"=>1, "adjective"=>1, "noun"=>1}