class in instance_eval -- what the namespace?

S

Simon Chiang

I'm confused as to how the parent constant is determined when you
define a class within an instance_eval. It appears that sometimes
ruby decides to use a nameless, perhaps temporary class as the parent
constant.

Interestingly enough, the behavior is different when you use a block
vs a string, and ruby implementation to implementation. For example
consider this script:

[script.rb]
obj = Object.new

obj.instance_eval do
class A; end
puts A
end
puts A rescue puts $!.message

obj.instance_eval %q{
class B; end
puts B
}
puts B rescue puts $!.message

Running this across several implementations produces a variety of
results:

% rvm ruby script.rb
jruby-1.4.0: jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2009-11-02
69fbfa3) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_17) [x86_64-java]
A
A
#<Class:01x3a98350a>::B
uninitialized constant B
rbx-1.0.0-rc4: rubinius 1.0.0-rc4 (1.8.7 release 2010-03-31 JI)
[x86_64-apple-darwin10.3.0]
A
A
B
B
ruby-1.8.7-p249: ruby 1.8.7 (2010-01-10 patchlevel 249) [i686-
darwin10.2.0]
A
A
#<Class:0x10019c3b8>::B
uninitialized constant B
ruby-1.9.1-p378: ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-
darwin10.2.0]
#<Class:0x000001008481e0>::A
uninitialized constant A
#<Class:0x000001008481e0>::B
uninitialized constant B

Any thoughts? And specifically, does anyone know of a way to set the
default namespace for the class keyword? Specifying the full constant
name like 'class ::A' works to assign the constants and uniformly
produce a rubinius-like output but I was wondering if there is another
way.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top