1

I am testing a method with multiple arguments. For some reason, Ruby will run fine if I have just one argument to the calculate() method, but when I add a second, it causes an unexpected end of input error.

This is the code:

def set_weights
    actual_weight = @desired_weight.to_i - 45
    calculate (actual_weight, 65)
end

def calculate (remaining_weight, plate_weight)
end

The error message is:

    weights.rb:31: syntax error, unexpected ',', expecting ')'
    calculate (actual_weight, 45)
                             ^

If I remove the second argument, I get no errors.

def set_weights
    actual_weight = @desired_weight.to_i - 45
    calculate (actual_weight)
end

def calculate (remaining_weight)

end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
JoYKim
  • 11
  • 1
  • 1
    you should remove space between `calculate` and `(remaining_weight, place_weight)` – Oleksandr Holubenko Jan 23 '17 at 19:53
  • That worked, thanks! Does ruby take into account white space when calling and declaring methods? – JoYKim Jan 23 '17 at 19:55
  • [Here](http://stackoverflow.com/questions/26480823/why-does-white-space-affect-ruby-function-calls) you can get an explanation for that behaviour – jmm Jan 23 '17 at 20:30

2 Answers2

1

Define a function:

irb(main):012:0> def add(x, y) x+y end 
`=> nil

If you call it without a space between the arguments and the function:

irb(main):013:0> add(5,6)
=> 11

With the space:

irb(main):014:0> add (5,6)
SyntaxError: (irb):14: syntax error, unexpected ',', expecting ')'
add (5,6)
       ^
from /usr/bin/irb:12:in `<main>'

The extra space before the argument list causes the interpreter to throw a SyntaxError. Since ruby functions can be run with or without parens, including a space makes the interpreter think it is about to receive arguments for the function - instead it receives a tuple (5,6).

Remove the space and your code will run correctly.

0

Remove the extra space before the method call, like this:

def set_weights
    actual_weight = @desired_weight.to_i - 45
    calculate(actual_weight, 65)
end

def calculate (remaining_weight, plate_weight)
end
jmm
  • 1,044
  • 2
  • 12
  • 38