On Sun, Jul 30, 2006 at 07:44:06PM +0900, Karel M. wrote:
This code:
puts eval(“var” ).class
puts eval(“var”).class.instance_methods(false).sort
var = “”;
produces:
NilClass
[…]
which is exactly what I would expect in the first case also.
When the “var” String is eval()ed, var="" has already been parsed. Ruby
already knows that var refers to a local variable, so “var” will be
interpreted correspondingly. When this happens, var hasn’t been assigned
to,
though, so the returned value is nil.
This is what’s happening:
eval(“a”) # => nil
a = 1 # since the parser has seen this, “a” will be a local
# in code parsed from now on. Its value is nil until it is
# initialized.
Compare it to the following situation, where the block is parsed before
you
assign to a:
instance_eval { a } # =>
a = nil
~> -:1: undefined local variable or method `a’ for main:Object