问题描述:

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

In Ruby versions:

2.1.5p273 (2014-11-13 revision 48405) [x64-mingw32]

1.9.3p194 (2012-04-20) [i386-mingw32]

The output is

#0

#1

I would expect for all the numbers in the array to be summed and multipled.

What is the reason that the actual multiplication and summation doesn't happen.

网友答案:

You never use the return value of your block, that comes out of yield. It should be along the lines of this:

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

And I have to note that you're reinventing the wheel. Your accumulation function is already implemented in Ruby standard library and is called reduce or inject (either way works):

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(:*)
网友答案:

Set result to the value obtained from yield:

def accum(start, items) 
    result, items = start, items.dup
    result = yield(result, items.pop) until items.empty?
    result
end
相关阅读:
Top