syntax error, unexpected '=', expecting ')'
I am very new at Ruby and programming and I am trying to write this simple function below
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
Solution 1:
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". So, if you want to keep y
mandatory it should be something like
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.