I have a hash example which has two element (section_one and section_two) in Ruby. I want to sum up each element separately and estimate each element average.
My hash:
class_grades = {
:section_one => [88, 74, 64],
:section_two => [99, 100]
}
I have tried on this code
sum = 0
class_grades.each do |key, value|
value.each do |value1|
sum += value1
end
puts "#{key}: #{sum.to_f}"
end
but it turns out with the result:
section_one: 226.0
section_two: 425.0
I have a problem to sum up each element separately. It estimates firs element and goes on. Could you help me to fix this problem.
First, with minimum editing of your code:
class_grades.each do |key, value|
sum = 0
value.each do |value1|
sum += value1
end
puts "#{key}: #{sum.to_f}"
end
But I'll recommend you do someth about:
class_grades.each do |key, value|
puts "#{key}: #{value.inject(:+).to_f}"
end
You should set to zero sum
at the beginning of your loop
class_grades.each do |key, value|
sum = 0
value.each do |value1|
sum += value1
end
puts "#{key}: #{sum.to_f}"
end
There is a more idiomatic way to get the sum from an enumerable
class_grades.each do |key, value|
sum = value.inject(0, :+)
puts "#{key}: #{sum.to_f}"
end
And, you don't need that .to_f
. 1 + 2.5
gets 3.5
class_grades.each do |key, value|
sum = value.inject(0, :+)
puts "#{key}: #{sum}"
end
Here's another way to do this:
class_grades.map { |k,v| [k, v.sum.fdiv(v.size).round(1)] }.to_h
#=> { :section_one => 75.3, :section_two => 99.5 }
Key methods: Array#sum
(>2.4.0), Integer#fdiv
and Float#round
. See ruby-doc.org for more info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.