2017-01-23 45 views
1

我正在测试一个具有多个参数的方法。出于某种原因,如果我只有一个参数calculate()方法,Ruby会运行良好,但是当我添加第二个参数时,它会导致意外的输入错误结束。如何在添加额外的方法参数时避免意外的输入错误结束

这是代码:

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

def calculate (remaining_weight, plate_weight) 
end 

的错误信息是:

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

如果我删除了第二个参数,我没有得到任何错误。

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

def calculate (remaining_weight) 

end 
+1

你应该删除'calculate'和'(remaining_weight,place_weight)'之间的空格' –

+0

这工作,谢谢!调用和声明方法时,ruby是否考虑了空白区域? – JoYKim

+0

[Here](http://stackoverflow.com/questions/26480823/why-does-white-space-affect-ruby-function-calls)你可以得到这种行为的解释 – jmm

回答

0

的方法调用之前删除多余的空间,就像这样:

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

def calculate (remaining_weight, plate_weight) 
end 
1

定义一个函数:

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

如果你不使用的参数和功能之间的空间:

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

W ith空格:

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

参数列表之前的额外空间会导致解释器抛出SyntaxError。由于ruby函数可以在有或没有parens的情况下运行,包括一个空格让解释器认为它将接收函数的参数 - 相反,它会接收一个元组(5,6)

删除空间,您的代码将正常运行。