gpt4 book ai didi

ruby-on-rails - Ruby on Rails 数组迭代

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:06 25 4
gpt4 key购买 nike

我是 Rails(和 ruby​​)的新手。遍历数组以计算变量总和的标准方法是什么。

例如对于一个月的总费用,首先是一个数组:

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

或者用一个 block

total = 0.0
expenses_this_month.each do |expense|
total += expense.cost
end
return total

我知道默认情况下会返回 ruby​​ 方法的最后一行,所以一定有更好的写法吗?

最佳答案

inject 方法会很好用,就像 Doug 所建议的那样。但是,通常最好尽可能在数据库中执行此类操作。 ActiveRecord 为此提供了一个简单的接口(interface)。

total = Expenses.sum :cost, :conditions => {
:date => (Date.today.beginning_of_month..Date.today.end_of_month)
}

请注意,您也可以使用 Range 对象代替 SQL 插值。

如果您出于其他原因加载所有 Expense 对象,那么注入(inject)方法当然没问题。

关于ruby-on-rails - Ruby on Rails 数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2024936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com