简体   繁体   中英

How can I improve this sum with reduce method

I would like to improve this sum using the reduce method, but I saw that works well for summing but also I have to do a subtract:

final = 0
@status.each do |data|
  final = final + data['pending_increase'] - data['pending_decrease']
end

The method I want to use is Enumerable#reduce

Something like this:

@status.reduce(0){|sum, data| sum + data['pending_increase'] - data['pending_decrease']}

or

@status.map{|data| data['pending_increase'] - data['pending_decrease']}.reduce(0, :+)

This will work too (as the initial seed is 0 ), but doesn't use reduce as requested

@status.sum{|data| data['pending_increase'] - data['pending_decrease']}

This two expressions are equivalent, being sum shorter and simpler than map / reduce

enum.sum{...} == enum.map{...}.reduce(0, :+)

如果这是在rails应用程序中,您可以这样做:

@status.map{|data| data['pending_increase'] - data['pending_decrease']}.sum

You could first compute the differences, then sum them:

@status.map { |data| data['pending_increase'] - data['pending_decrease'] }.reduce(:+)

but this has the disadvantage of creating a temporary array.

Just sayin'.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM