Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
两个相似的句子有不同的行为。可以吗?
比较:
a = 123 unless defined? a a # => nil
但...
unless defined? b b = 123 end b # => 123
是的,这是正确的行为。局部变量是nil在赋值之前创建和初始化的。所以这段代码
nil
大致相当于
a = nil a = 123 unless defined? a # `a` is not undefined anymore. a # => nil
另一个示例(即使c未在此行之前定义,此代码也不会抛出 a NameError)。
c
NameError
c = 2 unless c # => 2