class context

S

Sebastian Krause

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:in `class_exec'
from (irb):4
from /usr/bin/irb:12:in `<main>'
irb(main):005:0> C1.class_eval "p Const" # furthermore this
42
=> 42
 
R

Robert Klemme

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 =3D 666
class C1; Const =3D 42; end
C1.class_eval { p Const }
CODE
666
17:03:56 ~$
----
irb(main):001:0> RUBY_VERSION
=3D> "1.9.2"
irb(main):002:0> class C1; Const =3D 42; end
=3D> 42
irb(main):003:0> class C1; p Const; end
42
=3D> 42
irb(main):004:0> C1.class_exec { p Const }
NameError: uninitialized constant Class::Const
=A0 =A0from (irb):4:in `block in irb_binding'
=A0 =A0from (irb):4:in `class_exec'
=A0 =A0from (irb):4
=A0 =A0from /usr/bin/irb:12:in `<main>'
irb(main):005:0> C1.class_eval "p Const" =A0 =A0 =A0 # furthermore this
42
=3D> 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

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top