"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

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

···

from :0

try

   class << x
     def foo() 42 end
   end

or

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

regards.

-a

···

On Wed, 3 May 2006, Joshua Haberman wrote:

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

I try:

x = Class.new

class x
def foo
end
end

--
be kind whenever possible... it is always possible.
- h.h. the 14th dali lama

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.

···

On 5/2/06, Joshua Haberman <joshua@reverberate.org> wrote:

--
Lou

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, ara.t.howard@noaa.gov <ara.t.howard@noaa.gov> wrote:

try

   class << x
     def foo() 42 end
   end