Ruby parentheses around arguments in a method definition

I know that many ruby ​​stylists insist on parentheses around method arguments for method definitions. And I understand how brackets are sometimes syntactically needed for method calls.

But can anyone provide an example of why Ruby ever needs parentheses around arguments to define a method? Basically, I'm looking for a reason other than "it looks better."

+7
source share
2 answers

Another example: if you want to pass a hash as an argument, for example

This does not work:

MyTable.update_all { col_a: 1, col_b: 2 } 

because {} is for the block, not for the hash

Adding pairs really works.

 MyTable.update_all({ col_a: 1, col_b: 2 }) 

In the case of update_all, it takes up to 3 hashes as arguments, so it is important to specify which values ​​are included in the hash.

-2
source

If you had neither parentheses nor a semicolon as indicated in this comment , that would be ambiguous.

 def foo a end # => Error because it is amgiguous. # Is this a method `foo` that takes no argument with the body `a`, or # Is this a method `foo` that takes an argument `a`? 

Also, if you want to use compound arguments, you cannot omit parentheses:

 def foo(a, b), c p [a, b, c] end # => Error def foo((a, b), c) p [a, b, c] end foo([1, 2], 3) # => [1, 2, 3] 
+16
source

All Articles