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
有帮助吗?

解决方案

Maybe using the common "map" and "reduce" functions is more clear?

taxes.map { |t| t[:rate] }.reduce(:+) # => 3.0 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top