[英]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]} grade_hash = {帐单:[100,95,92],坦率:[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. 我尝试在末尾进行.each迭代,但这似乎不起作用,因为我不想真正进行迭代,我只想从每个创建的数组中求和然后求平均值。
Thoughts? 有什么想法吗?
Try this one 试试这个
def average(grade_hash)
grades = grade_hash.values.flatten
grades.sum / grades.size.to_f
end
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...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.