开发者

Ruby: Multi-line conditional syntax: how do I do it?

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 me开发者_如何学JAVAsses 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?


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?
            )
          ) 


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.


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)


Try this:

sub = (comparer == compared and another_question?)
result = (not question?) and (condition or sub)

No need to make the whole thing one expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜