How do I create a class instance from a string name in ruby?
In rails you can just do:
clazz = 'ExampleClass'.constantize
In pure ruby:
clazz = Object.const_get('ExampleClass')
with modules:
module Foo
class Bar
end
end
you would use
> clazz = 'Foo::Bar'.split('::').inject(Object) {|o,c| o.const_get c}
=> Foo::Bar
> clazz.new
=> #<Foo::Bar:0x0000010110a4f8>
Very simple in Rails: use String#constantize
class_name = "MyClass"
instance = class_name.constantize.new
Try this:
Kernel.const_get("MyClass").new
Then to loop through an object's instance variables:
obj.instance_variables.each do |v|
# do something
end