On 10/27/06, matt neuburg <matt / tidbits.com> wrote:
> class BigGuy
>   def setup
>     @favorites = "bluto"
>   end
>   def initialize
>     setup
>     p @favorites
>   end
>   class MiddleGuy < BigGuy
>   end
>   def self.make_subclass(what)
>     p = Proc.new {@favorites = what}
>     MiddleGuy.send( :define_method, :setup, p )
>     return MiddleGuy.clone
>   end
> end

You can do away with the explicit "MiddleGuy" class and the clone
call, by just creating an anonymous class on each invocation:

  class BigGuy
    def setup
      @favorites = "bluto"
    end

    def initialize
      setup
      p @favorites
    end

    def self.with_favorites(favorites)
      Class.new(self) do
        define_method(:setup) do
          @favorites = favorites
        end
      end
    end
  end

And while we're at it, if the only purpose of the on-the-fly class was
for the subclass to inherit from, why not make the subclass *be* the
on-the-fly class:

  LittleGuy = BigGuy.with_favorites('popeye')
  DevilishGuy = BigGuy.with_favorites(666)

Then the following code produces the same output as yours above:

  BigGuy.new #=> "bluto"
  LittleGuy.new #=> "popeye"
  BigGuy.new #=> "bluto"
  DevilishGuy.new #=> 666
  LittleGuy.new #=> "popeye"

Jacob Fugal