Define_class and get_class

Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:

name = "A"
define_class(name) do
   def say_hi
     p "hi"
   end
   .
end
get_class(name).new.say_hi

I would like the above syntax better than the current way of doing it.

name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
   def say_hi
     p "hi"
   end
   .
end
klass.new.say_hi

-Mushtaq

Mushtaq Ahmed wrote:

Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:

name = "A"
define_class(name) do
   def say_hi
     p "hi"
   end
   .
   .
end
get_class(name).new.say_hi

I would like the above syntax better than the current way of doing it.

name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
   def say_hi
     p "hi"
   end
   .
   .
end
klass.new.say_hi

-Mushtaq

cl = Class.new do
  def say_hi() puts "hi!" end
end

cl.new.say_hi

hi!
=> nil

cl.name

=> ""

A=cl

=> A

cl.name

=> "A"

Does that help?

Kind regards

    robert

This is unnecessary.

  A = Class.new
  A.class_eval do
    def say_hi
      p "hi"
    end
  end

And as of 1.8, we can now also write:

  A = Class.new do
    def say_hi
      p "hi"
    end
  end

Paul

···

On Fri, Oct 21, 2005 at 07:45:07PM +0900, Mushtaq Ahmed wrote:

name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
  def say_hi
    p "hi"
  end
  .
  .
end
klass.new.say_hi

A = Class.new {
   # ...
}

T.

Mushtaq Ahmed wrote:

Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:

name = "A"
define_class(name) do
   def say_hi
     p "hi"
   end
   .
   .
end
get_class(name).new.say_hi

I would like the above syntax better than the current way of doing it.

module Kernel
  def define_class(name, &blk)
    klass = self.class.const_set(name, Class.new(&blk))
  end

  def get_class(name)
    self.class.const_get(name)
  end
end

name = 'D'

klass = define_class(name) do
   def say_hi
     p "hi #{self.class.name}"
   end
end

get_class(name).new.say_hi #-> "hi D"

daz

Trans wrote:

A = Class.new {
   # ...
}

T.

Not the same thing. I want to decide the class name at runtime. It could be A, B, C or whatever.

-Mushtaq

Mushtaq Ahmed wrote:

Trans wrote:

A = Class.new {
   # ...
}

T.

Not the same thing. I want to decide the class name at runtime. It
could be A, B, C or whatever.

cl = Class.new do
  def foo() "bar" end
end

Object.const_set("AnyName", cl)
....

    robert