Closed. This question is opinion-based. It is not currently accepting answers. Learn more
想改进这个问题吗更新问题,以便editing this post可以用事实和引用来回答。
5年前关闭。
我有一个arrayhash值:

> taxes = [{:name=>"foo", :rate=>0.5}, {:name=>"bar", :rate=>2.5}]
=> [{:name=>"foo", :rate=>0.5}, {:name=>"bar", :rate=>2.5}]

这是对费率的总结:
> taxes.reduce(0) {|sum,element|sum + element[:rate]}
=> 3.0

有没有其他方法可以更容易理解和简洁?
**编辑**
用于比较(是的,我意识到这只是一个数组):
>> [1,2,3].reduce(:+)
=> 6

最佳答案

也许使用普通的“map”和“reduce”函数更清楚?

taxes.map { |t| t[:rate] }.reduce(:+) # => 3.0

关于ruby - 减少Ruby的哈希数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21866328/

10-13 04:52