Skip to content

Instantly share code, notes, and snippets.

@gabriel-dehan
Created December 3, 2014 22:29
Show Gist options
  • Save gabriel-dehan/92a5ea4c297f342c9f14 to your computer and use it in GitHub Desktop.
Save gabriel-dehan/92a5ea4c297f342c9f14 to your computer and use it in GitHub Desktop.
Equalize two number hashes
Equalizes two hashes
#
# {"25-34"=>76, "35-44"=>16, "18-24"=>4, "65"=>4}
# {"35-44"=>6.0, "13-17"=>20.0, "18-24"=>59.4, "25-34"=>14.6}
#
# Equalize Hashes =>
#
# {"25-34"=>14.6, "35-44"=>6.0, "18-24"=>59.4, "65"=>0.0, "13-17"=>20.0}
# {"25-34"=>76, "35-44"=>16, "18-24"=>4, "65"=>4, "13-17"=>0.0}
#
def equalize_hashes(hash, other_hash)
# Bit hard to understand
keys = (hash.keys + other_hash.keys).uniq
new_hash = {}
new_other_hash = {}
keys.each do |key|
new_hash[key] = hash[key] if hash[key] && (new_hash[key] == 0 || new_hash[key].nil?)
new_hash[key] = 0.0 if other_hash[key] && (new_hash[key] == 0 || new_hash[key].nil?)
new_other_hash[key] = 0.0 if hash[key] && (new_other_hash[key] == 0 || new_other_hash[key].nil?)
new_other_hash[key] = other_hash[key] if other_hash[key] && (new_other_hash[key] == 0 || new_other_hash[key].nil?)
end
[new_hash, new_other_hash]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment