0

以下代码:

def array_sum(*n)
  sum = 0
  0.upto(a.length-1) do |i|
    sum += n[i]
  end
  return sum
end

a = (1..5).to_a
puts array_sum(a)

给了我一个模棱两可的错误:

“/Users/Josh/Documents/Aptana Studio 3 Workspace/Test/Euler7.cgi:10:in array_sum': undefined local variable or methoda' for main:Object (NameError) from /Users/Josh/Documents/Aptana Studio 3 Workspace/Test/Euler7.cgi: 17"

谁能帮我吗?

4

2 回答 2

7

错误没有任何含糊之处。您可能打算写n.length - 1而不是a.length - 1.

于 2013-04-10T17:48:08.433 回答
2

虽然 Sergio Tulentsev 的答案是合适的解决方案,但您可能也对该算法的单行实现感兴趣:

puts (1..5).reduce(:+)
于 2013-04-10T17:55:26.387 回答