对哈希数组中的值求和的更好方法 [英] Better way to sum values in an array of hashes
问题描述
我需要对数组哈希值求和,我找到了一种方法这里
I need to sum values in an array hashes and I found a way to do it here
但看起来 Ruby 应该有更优雅的方式.
but it sure seems like there should be a more elegant way in Ruby.
这是有效的;
sales = [{"sale_price"=>210000, "deed_type"=>"Warranty Deed"}, {"sale_price"=>268300, "deed_type"=>"Warranty Deed Joint"}]
total_sales = sales.inject(0) {|sum, hash| sum + hash["sale_price"]}
总计行不太易读.如果这样的事情有效,那就太好了;
The totals line is not very readable. It would be nice if something like this worked;
total_sales = sales.sum("sale_price")
这只是一厢情愿还是我忽略了更好的解决方案?
Is this just wishful thinking or am I overlooking a better solution?
推荐答案
我喜欢像这样使用 map/reduce 比喻:
I like using the map/reduce metaphor like so:
total_sales = sales.map {|s| s['sale_price']}.reduce(0, :+)
reduce 方法是inject 方法的同义词,我发现inject 这个名字和memo 组件有点混淆.它有我在上面使用的另一种形式来获取初始值和对用于组合/归约过程的方法调用的引用.
The reduce method is a synonym for the inject method, I find the name inject to be somewhat confusing with the memo component. It has another form I use above to take the initial value and a reference to a method call used for the combination/reduction process.
我认为映射值然后将它们减少到聚合的整体模式是众所周知的并且是自我记录的.
I think the overall pattern of mapping the values and then reducing them to an aggregate is well known and self-documenting.
使用符号 :+ 而不是 proc 引用 &:+
Use symbol :+ instead of proc reference &:+
这篇关于对哈希数组中的值求和的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!