當a
是不確定的,那麼a || 1
將拋出一個錯誤,但a = a || 1
不會。這是不是有點不一致?爲什麼在Ruby中,|| 1在未定義a時會引發錯誤,但a = a || 1不會?
irb(main):001:0> a
NameError: undefined local variable or method 'a' for main:Object
from (irb):1
from c:/ruby/bin/irb:12:in '<main>'
irb(main):002:0> a || 1
NameError: undefined local variable or method 'a' for main:Object
from (irb):2
from c:/ruby/bin/irb:12:in '<main>'
irb(main):003:0> a = a || 1
=> 1
重複http://stackoverflow.com/questions/1462407/ruby-edge-cases的 – 2010-06-06 23:20:52