Nested class, require


#1

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?


#2

On Thu, 22 Dec 2005 14:19:20 -0000, List R. removed_email_address@domain.invalid
wrote:

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?

I’ve just been playing with this a bit, and have updated the relevant
nuby
files:

http://roscopeco.co.uk/code/noob/flexi-class.html
http://roscopeco.co.uk/code/noob/require-include.html

I’m not sure it answers your question but it exercises these concepts :slight_smile:


#3

List R. wrote:

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.


#4

List R. wrote:

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