Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable getting initialized with nil

Tags:

ruby

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

like image 507
Mudassir Ali Avatar asked Mar 06 '13 06:03

Mudassir Ali


1 Answers

"[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.

like image 189
Tim Destan Avatar answered Nov 05 '22 22:11

Tim Destan