簡體   English   中英

Ruby:多行條件語法:我該怎么做?

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

我正在嘗試做什么:

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

目標是具有復雜和/或邏輯,並且仍然具有可讀性。

上面嘗試語法的問題在於它是如何在ruby的解析器中弄亂括號,所以控制台說錯誤在這個代碼不在的文件中。(雖然它在調用堆棧中)

沒有反斜杠,我得到這些:

syntax error, unexpected kAND, expecting kEND (SyntaxError)

 syntax error, unexpected kOR, expecting ')'

關於如何正確地做到這一點的任何想法?

another_question? \\反斜杠后刪除空格another_question? \\ another_question? \\ 您正在轉義空間而不是換行符,這會導致語法錯誤。

請注意,您不需要轉義每個換行符。

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

對於邏輯表達式,您應該使用&&|| ! ,不andornot

andornot應該僅被用於控制流。

一個原因是&&|| ! 優先級高於andor not

此博客文章中閱讀更多相關信息

確保每一行(除了最后一行)以一個運算符結束,因此解釋器“知道”將會有更多的操作數,例如

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

(用MRI 1.8.7測試)

試試這個:

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

不需要把整個事情做成一個表達。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM