On 9/27/05, Jonas Galvez <jonasgalvez / gmail.com> wrote:

> In Python I can do this:
>
>  >>> def create_class(name):
> ...     import new
> ...     c = new.classobj(name, tuple([object]), {})
> ...     def __init__(self, value):
> ...         self.value = value
> ...     setattr(c, "__init__", new.instancemethod(__init__, None, c))
> ...     return c
> ...
>  >>> MyClass = create_class("MyClass")
>  >>>
>  >>> obj = MyClass(value=10)
>  >>> print obj.value
> 10
>
> Is there anything similar in Ruby? Or do I need to use eval()?

You can create an anonymous class then associate it with a named constant:

klass = Class.new do
  attr_accessor :value
  def initialize(value)
    @value = value
  end
end

Object.const_set('MyClass', klass)

c = MyClass.new(10)
p c
#=> #<MyClass:0x2871320 @value=10>

Regards,

Sean