Ruby interpreter initializes a local variable with nil
when it sees an assignment to it. It initializes the local variable before it executes the assignment expression or even when the assignment is not reachable (as in the example below). This means your code initializes a
with nil
and then the expression a = nil
will evaluate to the right hand value.
a = 1 if false
a.nil? # => true
The first assignment expression is not executed, but a
is initialized with nil
.
You can find this behaviour documented in the Ruby assignment documentation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…