【问题标题】:Best way to solve sum of an array with .each用 .each 解决数组总和的最佳方法
【发布时间】:2016-07-29 17:21:34
【问题描述】:

以下是我为数组求和算法提交的一些代码。在这种情况下,我不得不使用 .each 但我觉得有更好的方法来做到这一点......

numbers = [5, 17, 2, 899, 101, 4, 66, 123, 98]
sum = 0
index = 0
numbers.each do |number|
  sum = sum + numbers[index]
  index += 1
end
puts sum

【问题讨论】:

  • 正常的方式是numbers.reduce(:+),但由于你必须使用each,我建议numbers.each.reduce(:+) #=> 1315
  • 我应该详细说明。 numbers.reduce(:+) 产生与numbers.reduce { |total, n| total + n } 相同的结果。见Enumerable#reduce(又名inject)。在你的 Ruby 教育中解释为什么这是真的还为时过早。现在,将前者视为编写后者的速记方式。 reduce 的接收者可以是数组 (numbers) 或枚举器 (numbers.each)。由于后者生成前者的元素,因此可以使用任何一个。尝试在 IRB 中运行 e = numbers.eache.to_a

标签: arrays ruby algorithm


【解决方案1】:

有。使用each时无需手动跟踪索引;你可以简单地做

numbers.each do |number|
  sum = sum + number
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2011-04-12
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2014-01-12
    相关资源
    最近更新 更多