[ruby] A compact way to get an average from a hash of arrays via /r/learnprogramming


[ruby] A compact way to get an average from a hash of arrays

I have the following hash of arrays (with meaningless data):

hash = Hash.new {|h,k| h[k] = []} hash[:a] = ["a",1] hash[:b] = ["b",2] hash[:c] = ["c",3] 

I want to get the average of the second array positions for each key. My current code is:

avg = 0 hash.each_pair { |k,v| avg += v[1] } avg = avg.to_f / hash.keys.length.to_f 

Is there a more efficient, or compressed method of getting the average?

Submitted July 12, 2017 at 01:54PM by urandom123
via reddit http://ift.tt/2t4FrtS

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s