Could someone help me understand what is happening here?
irb(main):001:0> a
NameError: undefined local variable or method a' for main:Object from (irb):1 irb(main):002:0> b NameError: undefined local variable or methodb’ for main:Object
from (irb):2
irb(main):003:0> c
NameError: undefined local variable or method c' for main:Object from (irb):3 irb(main):004:0> b = c NameError: undefined local variable or methodc’ for main:Object
from (irb):4
from :0
irb(main):005:0> a = a
=> nil
a is undefined, so why does “a = a” work instead of giving a NameError
like “b = c” does?
Also:
irb(main):006:0> b = c
NameError: undefined local variable or method `c’ for main:Object
from (irb):6
from :0
irb(main):007:0> b
=> nil
Why did b get initialized to nil if there was a NameError?
I was hoping it was for a cool reason or that it enabled some cool
usage, but seems like it’s more of an implementation consequence than
any intentional effect.
On Fri, Jan 27, 2012 at 6:40 PM, Navindra U. [email protected]
wrote:
Could someone help me understand what is happening here?
irb(main):005:0> a = a
=> nil
a is undefined, so why does “a = a” work instead of giving a NameError
like “b = c” does?
https://github.com/michaeledgar/ripper-plus
"Local variables are created immediately when the Ruby parser parses a
left-hand-side local variable. Before the right-hand-side is even
parsed, the local variable has been created. This also results in an
infamous anomaly:
def say_what?
x = ‘hello’ unless defined?(x)
puts x
end
say_what? prints a blank line! This is because as soon as the x on the
LHS is parsed, x is a local variable with value nil. By the time
defined?(x) is executed, x has long since been a local variable!"
On Fri, Jan 27, 2012 at 6:56 PM, Navindra U. [email protected]wrote:
Thanks for that.
I was hoping it was for a cool reason or that it enabled some cool
usage, but seems like it’s more of an implementation consequence than
any intentional effect.