Reputation: 8041
p b #undefined local variable or method b for main:Object
a = nil
if a and (b=3)
do_something_with b
end
p b # nil
Why is b getting the value nil
after the execution of if block, while expected result would be undefined local variable or method b for main:Object
, Does Ruby initialize all the variables to nil
in the memory beforehand ?
The same case with the following code
if nil
bb = 10
end
p bb # nil
someone please throw some light on how ruby initializes the variables and what is going on in this case, Thanks
Upvotes: 6
Views: 5761
Reputation: 2028
"[A local variable] is initialized if it appears on the left‐hand side (before the equals sign (U+003D)) of an assignment expression, even if the expression does not actually execute. Variables of the latter sort have the value nil."
EDIT: This answer used to point to a fairly good Ruby reference, which has apparently been replaced by a malware site. I've removed the link but retained the quotation of the answer.
Upvotes: 6