Drew
6/11/2006 7:38:00 AM
Charles L. Snyder wrote:
> Hi
>
> I am trying to solve a no doubt trivial problem
>
> given 2 hashes of identical length, with identical keys:
>
> h1 = {'dog'=>'blue, 'car'=>'red', boat=>'blue', 'house'=>'red',
> shoe=>'green'}
> h2 = {'dog'=>20, 'car' =>60, boat => 90, 'house' =>60, shoe => 70 }
>
> I want to find the sum of the values in the second hash (the numerical
> values); based on the values in the first hash:
>
> eg
> dogs are blue, and there are 20 dogs
> boats are blue, and there are 90 boats
> 90 + 20 = 110
> therefore blue => 110
>
> cars are red, and there are 60 cars
> house is red, and there are 60 houses
> therefore red => 120
>
> so the resulting hash is something like
>
> h3 = {'blue'=>110, 'red'=>120, ...}
>
> thanks - hopefully there is some easy way to do this I'm overlooking
>
>
> CLS
It seems to me as if you could create your third hash by simply
iterating through the first hash and using the second hash to update
the third hash for each item in the first. I'm somewhat new to Ruby
but I'll try to show what I mean using your example:
h1 = {'dog'=>'blue', 'car'=>'red', 'boat'=>'blue', 'house'=>'red',
'shoe'=>'green'}
h2 = {'dog'=>20, 'car'=>60, 'boat'=>90, 'house'=>60, 'shoe'=>70 }
h3 = {}
h1.each do |key, val|
if !h3.has_key? val
h3[val] = h2[key]
else
h3[val] += h2[key]
end
end
You can test to see if it's working how you want by using something
like:
h3.each {|key, val| puts "#{key}: #{val}"}
I'm pretty sure that's what you meant.