Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract values in hash from corresponding values in another hash

Tags:

ruby

hash

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.

like image 584
user1561696 Avatar asked Aug 14 '12 18:08

user1561696


People also ask

Can we get original value of hashed value?

So, no, you can not recreate the original data from it's hash. The only thing a hash is good for is to compare it with other hashes to see if the hashed data is identical or not.

Can a hash have multiple values Ruby?

Can a hash have multiple values Ruby? Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

What is modular hashing?

The most commonly used method for hashing integers is called modular hashing: we choose the array size M to be prime, and, for any positive integer key k, compute the remainder when dividing k by M. This function is very easy to compute (k % M, in Java), and is effective in dispersing the keys evenly between 0 and M-1.

How can you tell if a value is present in a hash?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .


1 Answers

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]}>
like image 160
Yasushi Shoji Avatar answered Oct 01 '22 20:10

Yasushi Shoji