Bug #16389
closedUnexpected tINTEGER in conditional expression
Description
I'm not sure that this is a bug, or simply an unexpected result of operator precedence, but I am seeing a result that appears to me to be an issue.
When putting a conditional expression after a command call using unless, I am seeing a syntax error when I believe the syntax should be valid. In particular:
def foo
puts "This method just has to exist"
end
foo unless (@bar&.nil? && @baz&.> 15)
This producessyntax error, unexpected tINTEGER, expecting ')' following the &.> safe navigation. I would not expect a syntax error here.
This seems a strange result to me, as foo unless (@bar&.nil? and @baz&.> 15) appears to work as expected, producing no syntax error.
Please let me know if I am missing something in either my expectation or the issue report. Thanks!
Updated by mame (Yusuke Endoh) about 6 years ago
- Status changed from Open to Closed
You need to parenthesize the argument 15.
foo unless (@bar&.nil? && @baz&.>(15))
I don't think that your expectation is wrong, but due to parser limitation, we cannot place a non-parenthesized method call as an argument of &&. It is a good practice to write parentheses for method calls, except some trivial cases (e.g., no-argument method calls and p arg).
Updated by mame (Yusuke Endoh) about 6 years ago
- Status changed from Closed to Rejected
Updated by codinganarchy (Matthew Tanous) about 6 years ago
mame (Yusuke Endoh) wrote:
I don't think that your expectation is wrong, but due to parser limitation, we cannot place a non-parenthesized method call as an argument of
&&. It is a good practice to write parentheses for method calls, except some trivial cases (e.g., no-argument method calls andp arg).
Just to clarify, if you don't mind, is this also due to the difference between .> (a method) and > (an operator)? I ask as foo unless (@bar&.nil? && @baz > 15) does not result in a syntax error, though using && @baz.> 15 will.
Updated by nobu (Nobuyoshi Nakada) about 6 years ago
codinganarchy (Matthew Tanous) wrote:
Just to clarify, if you don't mind, is this also due to the difference between
.>(a method) and>(an operator)? I ask asfoo unless (@bar&.nil? && @baz > 15)does not result in a syntax error, though using&& @baz.> 15will.
Yes, this is an issue of syntax precedence.
As comparison operators have higher precedence than logical operators, nil && bar > 15 is interpreted as nil && (bar > 15).
OTOH, a method call without parentheses has lower precedence, because its arguments may contain such logical expressions, so the combination of them, e.g, nil && p a && b, is ambiguous/confusing.