On 9/27/05, Jonas Galvez <jonasgalvez / gmail.com> wrote:
> Jonas Galvez wrote:
> > Is there anything similar in Ruby? Or do I need to use eval()?
> Hmm, apparently:
>
> MyClass = Class.new {
>       attr_accessor :value
>       def initialize(value)
>           self.value = value
>       end
> }
>
> o = MyClass.new(10)
> puts o.value
>
> But now I ask, how do I dynamically set its name ("MyClass") in the
> global namespace?

  def create_class(name, parent = nil)
    if parent
      klass = Class.new(parent)
    else
      klass = Class.new
    end
    klass.class_eval do
      def initialize(value)
        @value = value
      end

      attr_reader :value
    end

    Object.const_set(name, klass)

    klass
  end

  create_class('MyClass')
  obj = MyClass.new(10)
  puts obj.value


-a
--
Austin Ziegler * halostatue / gmail.com
               * Alternate: austin / halostatue.ca