Reputation: 65143
What I'm trying to do:
result = (not question?) \
and ( \
condition \
or ( \
comparer == compared and another_question? \
) \
)
The goal is to have complicated and / or logic and still have it be readable.
The problem with the above attempted syntax is that it some how messes up parenthesis in ruby's parser, so console says that the error is in a file that this code isn't in. (though it's in the call stack)
without the back slashes, I get these:
syntax error, unexpected kAND, expecting kEND (SyntaxError)
and
syntax error, unexpected kOR, expecting ')'
any ideas on how to properly do this?
Upvotes: 16
Views: 12197
Reputation: 11882
For logical expression, you should use &&
, ||
, !
, not and
, or
, not
.
and
, or
, not
should only be used for control-flow.
One reason is that &&
, ||
, !
have higher precedence than and
, or
, not
.
Read more about this in this blog post.
Upvotes: 13
Reputation: 77400
Remove the space after the backslash in another_question? \
. You're escaping the space rather than the newline, which causes a syntax error.
Note you don't need to escape every newline.
result = (not question?) \
and (
condition \
or (
comparer == compared and another_question?
)
)
Upvotes: 18
Reputation: 14086
Try this:
sub = (comparer == compared and another_question?)
result = (not question?) and (condition or sub)
No need to make the whole thing one expression.
Upvotes: 8
Reputation: 15954
Make sure each line (except the last) ends with an operator so the interpreter "knows" there will be more operands coming, e.g.
result = (not question?) and (
condition or
(comparer == compared and another_question?)
)
(tested with MRI 1.8.7)
Upvotes: 8