Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rule for the usage of parenthesis in method invocation?

Tags:

ruby

In invocation of a method, I could not omit the parenthesis in the following case:

t=[]
t.push {}
# => []  # I expected [{}]
t.push({})
# => [{}] 

What rules should I apply to avoid this?

like image 935
JCLL Avatar asked Sep 24 '15 08:09

JCLL


2 Answers

When you pass {} as the only argument (so there are no commas in the call), Ruby can not tell if you mean an empty hash or empty block, so you need to use parentheses to distinguish it:

t.push(){}
t.push({})

In other cases, good rule of thumb is that parentheses are needed if you use method call as argument directly i.e.

method arg0, arg1, other_method(arg01, arg02), arg2, arg3

When your method call gets even more nested, it is probably better to sparete method calls using local variables (or rethink your interfaces), i.e.

arg3 = other_method arg01, arg02
methods arg0, arg1, arg3, arg3, arg4
like image 58
Borsunho Avatar answered Oct 18 '22 10:10

Borsunho


You can switch to << from push to avoid this pitfall

t = []
t << {}
like image 27
Wand Maker Avatar answered Oct 18 '22 11:10

Wand Maker