def .. end is ok and class .. end is not ok .. Why??

K

Kyung won Cheon

module M
end

M.module_eval { def self.a; puts 'ok' end }
M.a
# => 'ok'

M.module_eval { class A; end }
M::A

# => uninitialized constant M::A (NameError)
 
P

Pit Capitain

2008/8/18 Kyung won Cheon said:
module M
end

M.module_eval { def self.a; puts 'ok' end }
M.a
# => 'ok'

M.module_eval { class A; end }
M::A

# => uninitialized constant M::A (NameError)

Constants (including class and module names) are lexically scoped (at
least in Ruby 1.8). Your code therefore defines the top-level class A.
If you want a nested constant, you could do

M.module_eval { class self::A; end }

Regards,
Pit
 

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,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top