Nested class, require

L

List Recv

How does ruby view nested classes - that is, to define a class within
another class?
I know that you cannot define a class within a method (not sure why)?

Also, is require the same thing as "copy and paste dynamically", or does
it drop down to the global namespace, or do something else?
 
B

Bob Showalter

List said:
is require the same thing as "copy and paste dynamically", or does
it drop down to the global namespace, or do something else?

It's the second. It's executed in the context of TOPLEVEL_BINDING.
 
D

Devin Mullins

List said:
How does ruby view nested classes - that is, to define a class within
another class?
I know that you cannot define a class within a method (not sure why)?
Yeah, you can nest a class within a class. That's because classes are
just constants, and classes can contain constants.

class Foo
def hi; puts 'hi!' end
end
Bar = Foo
Bar.new.hi #=> hi!
Bar::Bar = Bar
Bar::Bar.new.hi #=> hi!
Bar::Bar::Bar::Bar::Bar::Bar::Bar::Bar.new.hi #=> hi!

(Mind you, the normal way to do this is just to put the one class
definition inside the other. Look around for examples of this.)

You *can* define classes inside methods, just not using the normal
syntax. This has some consequences, for example on constant and class
variable scoping, but if you're dying to dynamically create classes...

def blah
thing = Class.new {
def zurr; puts 'fimmmmmmp' end
}
thing.new.zurr
end
blah

To assign this to a constant so you can use it elsewhere, you're going
to have to use the magic of const_set.
Also, is require the same thing as "copy and paste dynamically", or does
it drop down to the global namespace, or do something else?
Global. I've sort of got a hack to allow require'd code to go inside any
module/class you please, though it's definitely not for the queasy, and
it's not complete yet.

BTW, both of these are things you can test out very easily, using ruby
or irb at the commandline. Why aren't you doing that?

Devin
 

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
474,201
Messages
2,571,049
Members
47,652
Latest member
Campbellamy

Latest Threads

Top