Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby parentheses around arguments in a method definition

Tags:

ruby

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

But can anybody provide of example of why Ruby ever needs parentheses around arguments for a method definition? Basically, I'm looking for a reason besides "it looks better".

like image 237
justingordon Avatar asked Feb 05 '13 08:02

justingordon


1 Answers

If you had neither parentheses nor a semicolon as pointed out in this comment, it 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 when you want to use composite arguments, you cannot omit the 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]
like image 130
sawa Avatar answered Oct 07 '22 23:10

sawa