我正在尝试重构一个写得很糟糕的方法。该方法旨在扫描包含如下所示的余额哈希的数组:
{ amount: $123, month_end: '2013-01-31' }
并返回同一月底的所有余额,然后汇总金额。
def monthly_total(month)
balances = [ balance_1, balance_2 ]
# get and array of balances
balances_for_month = balances.select do |balance|
balance.month_end == month
end
# grab only the balances for the desired month
balance_amounts = balances_for_month.map do |balance|
balance.amount
end
#take all the balances for the month and sum them.
balance_amounts.inject{|sum,x| sum + x }
end
但必须有一种更时尚的方式来做到这一点。我怎样才能重构这个方法,让它循环一次原始数组,而不是创建新数组并循环遍历它们?