moshimoshi moshimoshi - 7 months ago 78
Ruby Question

Classify a Ruby string

I have a program that create classes which looks like:

MyClass = Class.new do
def initialize; end
# ...
end


But I would like to name dynamically MyClass, from a string. And because it's for the name of a class, I would like to classify that string, for instance (thanks Rails methods):

"hello_world".classify # => "HelloWorld"


I don't know if in pure Ruby there is a method for that.

Thank you

Answer

Not sure if your question is only about constructing a camelcased string, or also about assigning a newly created class to it. Because, for the latter, you should use Module::const_set method:

class_name = 'MyClass'
#=> "MyClass"
klass = Class.new do
  def foo
    "foo"
  end
end
#=> #<Class:0xa093a68>
Object.const_set class_name, klass
#=> Module::MyClass
MyClass.new.foo
#=> "foo"