[英]Ruby 2.2.4 lexing an assignment in a conditional
這兩行代碼有什么區別?
a = (b if (b = "test"))
a = b if (b = "test")
第一個運行正常,並將a
和b
都設置為test
,但是第二個拋出錯誤:
NameError:main:Object的未定義局部變量或方法“ b”
我以為對於第二行,Ruby將首先評估b = "test"
,然后評估if "test"
,最后評估b = "test"
a = b
。 實際發生了什么?
(Ruby版本2.2.4)
兩條線都行不通。 這兩行都將起作用。 它是schrödinger表達式:)。
您可以在新的repl中運行兩次:
a = b if b = "test"
#=> NameError: undefined local variable or method `b' for main:Object
a = b if b = "test"
#=> "test"
讓我們深入了解,打開一個新的repl:
defined(b)
#=> nil
a = b if b = "test"
#=> NameError: undefined local variable or method `b' for main:Object
defined(b)
#=> local-variable
b
#=> "test"
a = b if b = "test"
#=> "test"
因此,實際上Ruby評估了b = "test"
部分並在當前范圍內定義了此變量。 兩個表達式a = b
和if b = "test"
都被執行。 更重要的是,如果語句在賦值語句之前執行:
c = p("assignment") && b if b = p("if") && "test"
#=> "if"
#=> "assignment"
#=> NameError: undefined local variable or method `b' for main:Object
但是b
變量在初次評估時未在賦值語句的范圍內定義。 在第二種方法中,已經定義好了,因此您收到了正確的結果。
因此, 切勿以這種方式進行作業
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.