Class context

I thought that the block in the class_exec-method would be executed as
if it appeared within
a class definition. That seems naive as I discovered the following.

Why does an error occur here?


irb(main):001:0> RUBY_VERSION
=> “1.9.2”
irb(main):002:0> class C1; Const = 42; end
=> 42
irb(main):003:0> class C1; p Const; end
42
=> 42
irb(main):004:0> C1.class_exec { p Const }
NameError: uninitialized constant Class::Const
from (irb):4:in block in irb_binding' from (irb):4:inclass_exec’
from (irb):4
from /usr/bin/irb:12:in `’
irb(main):005:0> C1.class_eval “p Const” # furthermore this
42
=> 42

On Tue, Jan 18, 2011 at 4:52 PM, Sebastian K. [email protected]
wrote:

I thought that the block in the class_exec-method would be executed as if
it appeared within
a class definition. That seems naive as I discovered the following.

Why does an error occur here?

Because const lookup works statically. In your example actually
::Const is searched - but not found.

17:03:32 ~$ ruby19 <<CODE

Const = 666
class C1; Const = 42; end
C1.class_eval { p Const }
CODE
666
17:03:56 ~$

from (irb):4:in block in irb_binding' from (irb):4:in class_exec’
from (irb):4
from /usr/bin/irb:12:in `’
irb(main):005:0> C1.class_eval “p Const” # furthermore this
42
=> 42

It’s different for non compiled code as you show in the last example.
Here the lookup path is resolved at compile time of the String “p
Const”, i.e. not initial compile time of the script. The string is
compiled inside class_eval.

Kind regards

robert