return a = b if !a.nil?
return 'oh'
is mostly equivalent to
if !a.nil?
return a = b
end
return 'oh'
As such, Ruby first tests whether a
is not nil (which is false because a
is in fact nil
there as it had not been assigned a value yet). Because of that, the body of the if
is not executed and the execution follows along to the return 'oh'
.
The more important question here is however: why did this work at all and did not result in an error such as
NameError: undefined local variable or method `a'
when trying to access the a
variable in the if
, even though it was not initialized before.
This works because Ruby initializes variables with nil
if they appear on the left-hand side of an assignment in the code, even though the variable may not actually be assigned. This behavior is further explained in e.g. https://stackoverflow.com/a/12928261/421705.
Following this logic, your code thus only works with your original inline-if
but would fail with the block-form if
as with this longer form, a
would only be initialized within the if
block. Here, you would thus get the NoMethodError
.