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?
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
You can switch to <<
from push
to avoid this pitfall
t = []
t << {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With