1

This is what's up:

It seem I've got a syntax problem. Both of the following methods, which are similar to one another, load to irb fine. When I go to use them, though, they produce errors. Since I'm just learning this, I'm not only looking for a fix, I'm looking to understand why both return errors and how any fix works to solve the issues.

Thanks for the help,
TJ


First method:

def sum(*)
  
  i = 1
  total = sum[0]
  until sum[i] == nil
      total = total + sum[i]
      i += 1
  end
  puts total
  
end

Upon loading this file irb returns => nil, no errors. However, an attempt to use the method looks like:

sum 3, 58, 298, 2
Unknown error.

Writing the method directly in irb vs loading .rb file produces this error after line 3:

def sum(*) 
..   i = 1 
..   total = sum[0]
(eval):2: (eval):2: compile error (SyntaxError)
(eval):2: syntax error, unexpected $end, expecting kEND
total = sum[0]
              ^

Now, I see that it says SyntaxError but I do not know what the rest of the feedback means nor what proper syntax for this would be.


Second method:

def sum(*)
  
  i = 1
  total = sum[0]
  until i == sum.count
      total = total + sum[i]
      i += 1
  end
  puts total
  
end

This one produces all the same errors in the same ways as the first.

Community
  • 1
  • 1
tjfwalker
  • 494
  • 3
  • 18
  • 3
    If you're learning Ruby from a book or tutorial that has you using loops like this, you should find a better guide. Syntactic loops are extremely rare in idiomatic Ruby; prefer [`Enumerable`](http://ruby-doc.org/core-2.0/Enumerable.html) methods with blocks. `def sum(*values); values.reduce(:+); end` – dbenhur May 11 '13 at 22:06

1 Answers1

0

Try this instead:

def sum(*nums)
  sum = 0
  nums.each  { |num| sum += num }
  sum
end

sum(1, 2, 3)

I don't think `def sum(*) is valid Ruby syntax; you have to give your vararg a name.

Also, see this Stackoverflow question for an even shorter way to sum an array of numbers.

Community
  • 1
  • 1
Jimothy
  • 9,150
  • 5
  • 30
  • 33
  • It is valid syntax. It means: any number of arguments which don't have a name (and thus can't be referenced). IOW: it allows a method to ignore an arbitrary number of arguments. – Jörg W Mittag May 11 '13 at 17:21
  • @JörgWMittag: Interesting. What is the purpose of such a syntax? Why would one want a method which ignores its arguments? – Jimothy May 11 '13 at 18:13
  • @Jimothy An example might be concrete implementations of abstract classes or traits. There may be methods where the arguments are significant for one concrete implementation, but have no effect on behaviour of another. – dbenhur May 11 '13 at 21:59