从另一个散列值中的相应值中减去散列值 [英] Subtract values in hash from corresponding values in another hash

查看:101
本文介绍了从另一个散列值中的相应值中减去散列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够减去两个哈希值并在Ruby中获得第三个哈希值。



这两个哈希看起来像这样:

  h1 = {Cat=> 100,狗=> 5,鸟=> 2,Snake=> 10} 
h1.default = 0

h2 = {cat=> 50,狗=> 3,BIRD=> 4,鼠标=> 75,Snake=> 10}
h2.default = 0

我希望能够致电方法在h1上是这样的:

  h1.difference(h2)

并得到这个hash:

  {Cat => 50,狗=> 2,BIRD=> -2,鼠标=> -75} 

我想用这两个Hashes的键创建一个新的散列值,新散列是第一个散列中密钥的值减去第二个散列中该密钥的值。问题在于,无论键的情况如何,我都希望这种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 |值== 0}
结束
结束

这是好的,但是,不幸的是,结果并不是我想要的。



任何帮助将不胜感激。 解决方案



  require'set'

h1 = {Cat=> 100,狗=> 5,鸟=> 2,Snake=> 10}
h1.default = 0

h2 = {cat=> 50,狗=> 3,BIRD=> 4,鼠标=> 75,Snake=> 10}
h2.default = 0

p(h1.to_set - h2.to_set)
#=> #< Set:{[Cat,100],[Dog,5],[Bird,2]}>


I'd like to be able to subtract two hashes and get a third hash in Ruby.

The two hashes look like this:

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

I'd like to be able to call a method on h1 like this:

h1.difference(h2)

and get this hash as a result:

{"Cat" => 50, "Dog" => 2, "BIRD" => -2, "Mouse" => -75}

I'd like to create a new hash with keys from both Hashes and the values of the new hash to be the value of the key in the first hash minus the value of that key in the second hash. The catch is that I'd like this Hash method to work regardless of the case of the keys. In other words, I'd like "Cat" to match up with "cat".

Here's what I have so far:

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

This is OK, but, unfortunately, the result isn't what I want.

Any help would be appreciated.

解决方案

How about converting the hashes to sets.

require 'set'

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

p (h1.to_set - h2.to_set)
#=> #<Set: {["Cat", 100], ["Dog", 5], ["Bird", 2]}>

这篇关于从另一个散列值中的相应值中减去散列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆