我是Rails(和ruby)的新手。遍历一个数组以遍历一个变量的标准方式是什么?Ruby on Rails数组迭代
例如在一个月的总支出,第一个数组:
expenses_this_month = expenses.find :all,
:conditions => ['date >= ? and date <= ?',
Date.today.beginning_of_month, Date.today.end_of_month]
我已经是两个途径知道的这样做:
total = 0.0
for expense in expenses_this_month
total += expense.cost
end
return total
或块
total = 0.0
expenses_this_month.each do |expense|
total += expense.cost
end
return total
我m意识到ruby方法中的最后一行将被默认返回,所以必须有更好的书写方式?
谢谢你的建议。我不使用总和,因为成本是模型中的方法(不是数据库中的列),因为它是根据税率计算的。注入看起来像它会适用于我 – Ryan 2010-01-08 03:38:22