简体   繁体   English

语法错误,意外 '=',期待 ')'

[英]syntax error, unexpected '=', expecting ')'

I am very new at Ruby and programming and I am trying to write this simple function below我是 Ruby 和编程的新手,我正在尝试在下面编写这个简单的 function

def sum_square(x=0, y, z=0)
    p x**2 + y**2 + z**2
end

sum_square(2,3)

and i get this error syntax error, unexpected '=', expecting ')'我得到这个错误语法错误,意外'=',期待')'

I thought i could use optional argument here我想我可以在这里使用可选参数

Parameters with default values should be placed after parameters without default values or, as Tom Lord stated in comments, can be "placed anywhere else in the list, so long as they are all defined together".具有默认值的参数应该放在没有默认值的参数之后,或者正如 Tom Lord 在评论中所说,可以“放置在列表中的任何其他位置,只要它们都定义在一起”。 So, if you want to keep y mandatory it should be something like所以,如果你想保持y强制它应该是这样的

def sum_square(y, x=0, z=0)
  p x**2 + y**2 + z**2
end

But it can be confusing during calls, so you can switch to named params:但在调用过程中可能会造成混淆,因此您可以切换到命名参数:

def sum_square=(y, x:0, z:0)
  p x**2 + y**2 + z**2
end

# all these call are valid
sum_square(1) 
sum_square(1, x:2)
sum_square(1, z:2)
sum_square(1, x:2, z:3)

There are more possible ways to implement this function listed in comments with more general approach (for any number of inputs using * ) or with all params being named.有更多可能的方法来实现这个 function 列在评论中,使用更通用的方法(对于使用*的任意数量的输入)或命名所有参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM