I'm trying to refactor an really poorly written method. The method is meant to scan an array containing balance hashes that look like this:
{ amount: $123, month_end: '2013-01-31' }
and return all the balances with the same month end and then sum up the amounts.
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
But there's gotta be a sleeker way to do this. How can I restructure this method so that it loops over the original array once time, instead of creating new array and looping through them?