Reputation: 665
The following code:
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)
gives me an ambiguous error:
"/Users/Josh/Documents/Aptana Studio 3 Workspace/Test/Euler7.cgi:10:in
array_sum': undefined local variable or method
a' for main:Object (NameError) from /Users/Josh/Documents/Aptana Studio 3 Workspace/Test/Euler7.cgi:17"
Can anyone help me out?
Upvotes: 0
Views: 54
Reputation: 230296
There's nothing ambiguous about the error. You probably meant to write n.length - 1
instead of a.length - 1
.
Upvotes: 7
Reputation: 42903
While Sergio Tulentsev's answer is the appropriate solution here, you might be also interested in a one-line implementation of this algorithm:
puts (1..5).reduce(:+)
Upvotes: 2