user8387535
user8387535

Reputation: 63

Create an average of arrays from a hash in Ruby

So I have a hash like the following:

grade_hash = {bill: [100, 95, 92], frank: [67, 73, 84]}

I'm trying to find the average for both Bill and Frank.

I know that if I did something like:

def average (grade_hash)
grade_hash.transform_values{|num| num.reduce(:+)/num.size}
end

I can then pull out either Bill or Franks average.

How would I pull the average from all values (Bill and Frank's combined)?

I've attempted to do a .each at the end to iterate over but that doesn't seem to work because I wouldn't want to really iterate I would just want to take the sum from each created array then find an average.

Thoughts?

Upvotes: 0

Views: 193

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

def combined_average(grade_hash, *students)
  raise ArgumentError, "There must be at least one student" if students.empty?
  non_students = students - grade_hash.keys
  raise ArgumentError, "#{non_students} are not students" if non_students.any?
  arr = grade_hash.values_at(*students).flatten
  arr.sum.fdiv(arr.size).round(1)
end

grade_hash = {bill: [100, 95, 92], frank: [67, 73, 84], julie: [99, 99, 100] }

combined_average(grade_hash, :bill)                  #=> 95.7
combined_average(grade_hash, :frank)                 #=> 74.7
combined_average(grade_hash, :julie)                 #=> 99.3
combined_average(grade_hash, :bill, :frank)          #=> 85.2
combined_average(grade_hash, :bill, :frank, :julie)  #=> 89.9
combined_average(grade_hash, :bill, :mimi, :freddie)
  #=>ArgumentError: [:mimi, :freddie] are not students...
combined_average(grade_hash)
  #=> ArgumentError: There must be at least one student...

Upvotes: 1

Ursus
Ursus

Reputation: 30071

Try this one

def average(grade_hash)
  grades = grade_hash.values.flatten
  grades.sum / grades.size.to_f
end

Upvotes: 3

Related Questions