我希望能够减去两个哈希并在Ruby中获得第三个哈希值.
这两个哈希看起来像这样:
h1 = {"Cat" => 100,"Dog" => 5,"Bird" => 2,"Snake" => 10} h1.default = 0 h2 = {"cat" => 50,"dog" => 3,"BIRD" => 4,"Mouse" => 75,"Snake" => 10} h2.default = 0
h1.difference(h2)
并获得此哈希作为结果:
{"Cat" => 50,"Dog" => 2,"BIRD" => -2,"Mouse" => -75}
我想创建一个新哈希,其中包含来自两个哈希的键和新哈希的值,它们是第一个哈希中键的值减去第二个哈希中该键的值.问题是,无论密钥的情况如何,我都希望这种Hash方法能够正常工作.换句话说,我希望“猫”与“猫”匹配.
这是我到目前为止所拥有的:
class Hash def difference(another_hash) (keys + another_hash.keys).map { |key| key.strip }.uniq.inject(Hash.new(0)) { |acc,key| acc[key] = (self[key] - another_hash[key]); acc }.delete_if { |key,value| value == 0 } end end
这没关系,但不幸的是,结果并不是我想要的.
任何帮助,将不胜感激.
解决方法
如何将哈希转换为集合.
require 'set' h1 = {"Cat" => 100,"Snake" => 10} h2.default = 0 p (h1.to_set - h2.to_set) #=> #<Set: {["Cat",100],["Dog",5],["Bird",2]}>