简体   繁体   中英

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

Remove the space after the backslash in another_question? \\ 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, eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM