Chen Kinnrot
Chen Kinnrot

Reputation: 21015

Do average on hashes

lets say i got 3 hashes:

hash1={
a => 1,
b => 2,
c => 4
}


hash2={
b => 1,
c => 3
}

hash3={
a => 2,
b => 1,
c => 3,
d => 4
}

I want to average stuff to a new hash according to keys, so new hash will be

result={a=>1.5,b=>4/3,c=>10/3,d=>4}

meaning if key not exists in one hash we don't count it as 0.

is there an elegant way?

Upvotes: 2

Views: 85

Answers (1)

sawa
sawa

Reputation: 168269

result = {}
[hash1, hash2, hash3].each{|h| h.each{|k, v| (result[k] ||= []).push(v)}}
result.each{|k, v| result[k] = v.inject(:+).to_f/v.length}
result # =>
# {
#   a => 1.5,
#   b => 1.3333333333333333,
#   c => 3.3333333333333335,
#   d => 4.0
# }

Upvotes: 4

Related Questions