Ruby 在方法中传递多个参数
Ruby passing multiple parameters in methods
实际上我正在尝试使用第三个参数作为方法作为 get,第二个参数作为 *p 但它抛出错误
def ss(a,*b,method="GET")
puts a
end
ss("fff",98,"POST")
以上代码抛出错误
li.rb:1: syntax error, unexpected '=', expecting ')'
def ss(a,*b,method="GET")
^
li.rb:1: syntax error, unexpected ')', expecting end-of-input
如何使这个程序运行?
您需要这样做:
def ss(a,method="GET", *b)
puts a
end
当 splat 运算符用于接受多个输入时,它应该始终是方法的最后一个参数。此外,一个方法只能有一个 splat 参数。
感谢 Cary 对如何使用 splats 进行了清晰明了的解释:
Basically, the rule is that if it's unambiguous, it's OK--Ruby will
figure it out. If, however, you add a variable with a default value to
my example (def test(*a,b); p a; p b; end; test 1,2,3
), it becomes ambiguous, so Ruby will complain.
实际上我正在尝试使用第三个参数作为方法作为 get,第二个参数作为 *p 但它抛出错误
def ss(a,*b,method="GET")
puts a
end
ss("fff",98,"POST")
以上代码抛出错误
li.rb:1: syntax error, unexpected '=', expecting ')'
def ss(a,*b,method="GET")
^
li.rb:1: syntax error, unexpected ')', expecting end-of-input
如何使这个程序运行?
您需要这样做:
def ss(a,method="GET", *b)
puts a
end
当 splat 运算符用于接受多个输入时,它应该始终是方法的最后一个参数。此外,一个方法只能有一个 splat 参数。
感谢 Cary 对如何使用 splats 进行了清晰明了的解释:
Basically, the rule is that if it's unambiguous, it's OK--Ruby will figure it out. If, however, you add a variable with a default value to my example (
def test(*a,b); p a; p b; end; test 1,2,3
), it becomes ambiguous, so Ruby will complain.