ruby - Do average on hashes -
lets got 3 hashes:
hash1={ => 1, b => 2, c => 4 } hash2={ b => 1, c => 3 } hash3={ => 2, b => 1, c => 3, d => 4 } i want average stuff new hash according keys, new hash be
result={a=>1.5,b=>4/3,c=>10/3,d=>4} meaning if key not exists in 1 hash don't count 0.
is there elegant way?
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 # => # { # => 1.5, # b => 1.3333333333333333, # c => 3.3333333333333335, # d => 4.0 # }
Comments
Post a Comment