Maybe using the common "map" and "reduce" functions is more clear?
taxes.map { |t| t[:rate] }.reduce(:+) # => 3.0
Pregunta
I have an array
of hash
values:
> taxes = [{:name=>"foo", :rate=>0.5}, {:name=>"bar", :rate=>2.5}]
=> [{:name=>"foo", :rate=>0.5}, {:name=>"bar", :rate=>2.5}]
This works to summarize the rates:
> taxes.reduce(0) {|sum,element|sum + element[:rate]}
=> 3.0
Is there another way to do this that might be more understandable and succinct?
** edit **
For comparison (yes, I realize that this is just an array):
>> [1,2,3].reduce(:+)
=> 6
Solución
Maybe using the common "map" and "reduce" functions is more clear?
taxes.map { |t| t[:rate] }.reduce(:+) # => 3.0