5
我敢肯定有這種行爲我只是一個理由好奇它是什麼。
y = x # NameError: undefined local variable or method 'x'
x = x # => nil
我敢肯定有這種行爲我只是一個理由好奇它是什麼。
y = x # NameError: undefined local variable or method 'x'
x = x # => nil
這是由變量在Ruby中初始化的方式引起的,這種方式對於這種語言來說是相當獨特的。基本上,紅寶石初始化(創建)一個變量,如果它可能得到賦值。考慮下面這個例子:
if false
x = "hello"
end
x
肯定不會在這裏得到分配"hello"
字符串。但是,它仍然會得到與nil
從靜態分析程序初始化,它可能已被分配。
你舉的例子是類似的。因爲你指定的東西x
,它會被用在執行語句前nil
初始化。因此,在執行期間,x
實際上是nil
。
參見:http://stackoverflow.com/questions/8908050/why-is-a-a-nil-in-ruby –
謝謝,對不起,這是重複我找不到它。 – mechanicalfish