0

对我来说,我想不出更好的方法,但我相信有一个。是否有一种红宝石方式(意思是:优雅的方式)来执行以下方法实现?

def total(items)
  sum = 0
  items.each do |item|
    sum += item.value
  end
  sum
end
4

4 回答 4

3
items.inject(0) { |memo,item| memo + item.value }

似乎不需要将 0 作为初始值,但如果数组为空,它将返回此初始值。

第二种方法:

items.map(&:value).inject(0,:+)
于 2012-11-06T06:03:20.280 回答
3

map获取值,然后reduce使用加法:

def total(items)
  items.map(&:value).reduce(:+)
end
于 2012-11-06T06:23:27.507 回答
2

例如,您可以这样做

items.reduce{|sum, el| sum + el.value} 
于 2012-11-06T06:03:11.610 回答
1
def total(items)
  items.inject(0) do |total, item|
    total + item.value
  end
end
于 2012-11-06T06:06:23.683 回答