ruby中的累积函数不起作用

时间:2015-01-27 23:01:41

标签: ruby

def accum(start, items) 
    result, items = start, items.dup
    yield(result, items.pop) until items.empty?
    result
end

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
puts accum(0, numbers) { |a, b| a + b }
puts accum(1, numbers) { |a, b| a * b }

# 0
# 1

在Ruby版本中:
2.1.5p273(2014-11-13修订版48405)[x64-mingw32]
1.9.3p194(2012-04-20)[i386-mingw32]

输出

#0
#1

我希望数组中的所有数字能够求和并加倍 实际乘法和求和没有发生的原因是什么。

2 个答案:

答案 0 :(得分:3)

您永远不会使用来自yield的块的返回值。它应该是这样的:

result = yield(result, items.pop) until items.empty?

我必须注意到你正在重新发明轮子。您的累积函数已经在Ruby标准库中实现,称为reduceinject(两种方式都有效):

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
puts numbers.reduce {|a, b| a + b }
# But hey, we're just calling a single function with 2 args in that block
# Let's specify a symbol that corresponds to a function!
# Works pretty much the same way
puts numbers.reduce(:+)
# For multiplication too
puts numbers.reduce(:*)

答案 1 :(得分:1)

result设置为从yield获得的值:

def accum(start, items) 
    result, items = start, items.dup
    result = yield(result, items.pop) until items.empty?
    result
end