"classes are always open" for anonymous classes?

So you know how classes are always open? What about anonymous classes?

I try:

x = Class.new

class x
def foo
end
end

but get:

SyntaxError: compile error
(irb):2: class/module name must be CONSTANT
from (irb):5
from :0

I suppose class_eval is the equivalent?

x.class_eval {
def foo
end
}

my_x = x.new
my_x.foo

Unfortunately, that’s not as clear. I think that’s something I’m going
to have to live with, but any pointers for things I’m missing?

Also, is there any reason that the “class” declaration couldn’t accept
my first attempt at this (“class x; def foo; end; end”)?

Thanks,
Josh

On Wed, 3 May 2006, Joshua H. wrote:

So you know how classes are always open? What about anonymous classes?

I try:

x = Class.new

class x
def foo
end
end

try

class << x
def foo() 42 end
end

or

x = Class.new{
def foo() 42 end
}

regards.

-a

On 5/2/06, [email protected] [email protected] wrote:

try

class << x
def foo() 42 end
end

This one isn’t what he was looking for. The would be similar to doing:

class PhantomX
def self.foo; 42 end
end

Brian.

On 5/2/06, Joshua H. [email protected] wrote:

SyntaxError: compile error
(irb):2: class/module name must be CONSTANT
from (irb):5
from :0

Yep. The irb error message is actually giving a pretty good hint here.
Classes defined with the class keyword are always constants because they
start with an uppercase letter.

I suppose class_eval is the equivalent?

x.class_eval {
def foo
end
}

my_x = x.new
my_x.foo

Right again. You can also use that or you can assign to a constant:

X = x

class X
def foo
puts ‘bar’
end
end

y = x.new
y.bar

Although, in that case, you might as well assign to the constant in the
first place; although, if you continue down that road, there’s really no
point in declaring it anonymously.