How do I create a class instance from a string name in ruby?

RubyRuby on-Rails-3

Ruby Problem Overview


I have the name of a class and I want to create an instance of that class so that I can loop through each rails attribute that is present in the schema of that class.

How would I go about doing that?

  1. I have the name as a string of the class I want to check
  2. I guess I need to instantiate a class instance so that I can
  3. Loop through it's attributes and print them.

Ruby Solutions


Solution 1 - 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> 

Solution 2 - Ruby

Very simple in Rails: use String#constantize

class_name = "MyClass"
instance = class_name.constantize.new

Solution 3 - Ruby

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

Solution 4 - Ruby

module One
  module Two
    class Three
      def say_hi
        puts "say hi"
      end
    end
  end
end

one = Object.const_get "One"

puts one.class # => Module

three = One::Two.const_get "Three"

puts three.class # => Class

three.new.say_hi # => "say hi"

In ruby 2.0 and, possibly earlier releases, Object.const_get will recursively perform a lookup on a namespaces like Foo::Bar. The example above is when the namespace is known ahead of time and highlights the fact that const_get can be called on modules directly as opposed to exclusively on Object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmhenrixonView Question on Stackoverflow
Solution 1 - RubyWesView Answer on Stackoverflow
Solution 2 - RubyedgerunnerView Answer on Stackoverflow
Solution 3 - RubymbreiningView Answer on Stackoverflow
Solution 4 - RubyA-DubbView Answer on Stackoverflow