I'm just wondering where this syntax documented:
1 > 2 || raise("error")
I have tried use it as condition:
1 > 2 || p "test"
but it doesn't work:
SyntaxError: (irb):9: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
1 > 2 || p "test"
^
from C:/Ruby193/bin/irb:12:in `<main>'
What you have doesn't work because you need parenthesis:
1 > 2 || p("test")
Note that or
(and and
) has a different precedence than &&
/||
and thus will work without parenthesis (and with what you're doing makes more semantic sense):
1 > 2 or p "test"
as will unless
:
p "test" unless 1 > 2
It's just an inline way to say "raise an error if the condition is false". The || is just a common OR
operator, and the expression is evaluated using short-circuit evaluation. Nevertheless, for clarity purposes, I would prefer this:
raise("error") unless 1 > 2
Both executions do work, the problem is the exclusion of parenthesis on the p
. Running the code from IRB:
ruby-1.8.7-p302 :003 > 1 > 2 || raise("error")
RuntimeError: error
from (irb):3
By adding ( "test" ), the call works as expected:
ruby-1.8.7-p302 :004 > 1 > 2 || p("test")
"test"
What you're attempting to accomplish here is control flow rather than conditional logic. It's invalid syntax for conditional logic. Proper control flow will use the "and" and "or" constructs. This is what they are for and not, as is often incorrectly assumed, syntactic sugar replacements for && and || conditional operators. They are different, have different order of evaluation precedence and should be used in their right place. Examples:
1 > 2 or p 'no it is not'
2 > 1 and return
instance.exists? or not_found!
instance && instance.success? or raise FailureException, 'missing or unsuccessful'
Essentially, if you're trying to read true or false from the statement, use && and ||. If you're trying to execute a code path based upon a conditional evaluation, use and and or.