Josh Horowitz
Josh Horowitz

Reputation: 665

Getting a weird error in ruby while trying to pass an array to a method

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?

Upvotes: 0

Views: 54

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

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

Upvotes: 7

Koraktor
Koraktor

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

Related Questions