Forum: Ruby "classes are always open" for anonymous classes?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8d9023bdc5cbadf3221a0b66a46a34e6?d=identicon&s=25 Joshua Haberman (Guest)
on 2006-05-03 19:05
(Received via mailing list)
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
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2006-05-03 19:05
(Received via mailing list)
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

try

   class << x
     def foo() 42 end
   end

or

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


regards.

-a
B44ab09b79ee4a0cc4b4ca69e10eeb3a?d=identicon&s=25 Brian Mitchell (Guest)
on 2006-05-03 19:05
(Received via mailing list)
On 5/2/06, ara.t.howard@noaa.gov <ara.t.howard@noaa.gov> 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.
51a34236538906ab994cf9f2e533d14d?d=identicon&s=25 Lou Scoras (ljscoras)
on 2006-05-03 19:05
(Received via mailing list)
On 5/2/06, Joshua Haberman <joshua@reverberate.org> 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.
This topic is locked and can not be replied to.