I was playing with the assignment operation within if
blocks, and discovered the below result, which surprised me:
C:\>irb --simple-prompt
if false
x = 10
end
#=> nil
p x
nil
x.object_id
#=> 4
#=> nil
p y
NameError: undefined local variable or method `y' for main:Object
from (irb):5
from C:/Ruby193/bin/irb:12:in `<main>'
In the above code you can see that the x
local variable has been created even though it was only assigned to in the falsy if
block. I tried to to see the content of x
with p x
which forced me to believe that assignment was not done, but the x
variable exists. x.object_id
also proved that is the case.
Now my question is how that x
local variable was created even though the if
block entry point is closed forever intentionally?
I expected the output of p x
to be similar to the output from p y
. But instead I got a surprising answer from p x
.
Could someone explain to me how this concept works?
EDIT
No, here is another test. This is not the case with only local
variables. The same happened with instance
and class
variables also. See the below:
class Foo
def show
@X = 10 if false
p @X,"hi",@X.object_id
end
end
#=> nil
Foo.new.show
nil
"hi"
4
#=> [nil, "hi", 4]
class Foo
def self.show
@@X = 10 if false
p @@X,"hi",@@X.object_id
end
end
#=> nil
Foo.show
nil
"hi"
4
#=> [nil, "hi", 4]
Successful case :
class Foo
def self.show
@@X = 10 if true
p @@X,"hi",@@X.object_id
end
end
#=> nil
Foo.show
10
"hi"
4
#=> [10, "hi", 4]