0

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 methoda' for main:Object (NameError) from /Users/Josh/Documents/Aptana Studio 3 Workspace/Test/Euler7.cgi:17"

Can anyone help me out?

2 Answers 2

7

There's nothing ambiguous about the error. You probably meant to write n.length - 1 instead of a.length - 1.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you. No copy pasting, I'm just an idiot. I'll accept your answer as soon as stackOverFlow allows me
2

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(:+)

1 Comment

reduce(:+) means, call the method + while iterating over the elements of the array. You can also use :- or any other method (of the elements) that accepts an argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.