A
Achim Passen
Dear rubyists,
i'm fairly new to ruby, so please apologize if i'm missing something
obvious. I'm trying to figure out how constant lookup works and find
myself confused. Here we go:
class A; C=3 end
$a = A.new
$a.instance_eval "C" # => 3
$a.instance_eval {C}
# ~> NameError: uninitialized constant C [...]
This is ruby 1.8.6. My naive mental model of what's happening: constants
are evaluated statically before the block is passed along, and wrapping
it up as a string prevents the interpreter from looking inside too
early.
That seems to have changed with Ruby 1.9 (yesterday's trunk), but there
are a few surprises still:
def a_eval(&block) $a.instance_eval(&block) end
$a.instance_eval {C} # => 3
a_eval {C}
# ~> NameError: uninitialized constant C [...]
a_eval {instance_eval {C}} # => 3 -- ???
I gather it's a binding issue, but why should the binding of constants
(of anything, really) differ between inside "self.instance_eval { ... }"
and outside?
a_eval {binding}.eval("C")
# ~> NameError: uninitialized constant C [...]
a_eval {instance_eval{binding}}.eval("C") # => 3
$a.instance_eval {binding}.eval("C") # => 3
Can anybody shed some light on this? Thanks a lot!
Kind regards,
achim
i'm fairly new to ruby, so please apologize if i'm missing something
obvious. I'm trying to figure out how constant lookup works and find
myself confused. Here we go:
class A; C=3 end
$a = A.new
$a.instance_eval "C" # => 3
$a.instance_eval {C}
# ~> NameError: uninitialized constant C [...]
This is ruby 1.8.6. My naive mental model of what's happening: constants
are evaluated statically before the block is passed along, and wrapping
it up as a string prevents the interpreter from looking inside too
early.
That seems to have changed with Ruby 1.9 (yesterday's trunk), but there
are a few surprises still:
def a_eval(&block) $a.instance_eval(&block) end
$a.instance_eval {C} # => 3
a_eval {C}
# ~> NameError: uninitialized constant C [...]
a_eval {instance_eval {C}} # => 3 -- ???
I gather it's a binding issue, but why should the binding of constants
(of anything, really) differ between inside "self.instance_eval { ... }"
and outside?
a_eval {binding}.eval("C")
# ~> NameError: uninitialized constant C [...]
a_eval {instance_eval{binding}}.eval("C") # => 3
$a.instance_eval {binding}.eval("C") # => 3
Can anybody shed some light on this? Thanks a lot!
Kind regards,
achim