1

I need to create a class but the condition is, I will receive the class name in strings like shown below

 ["IndividualContact", "Legal"].each do |var|
      ind = var.new
    end

Now My expectation is, I need to call

IndividualContact.new and Legal.new but since var is a string variable, it's calling .new on a string like given below

"IndividualContact".new 

rather than calling

IndividualContact.new

Is there any way can I call as I expected?

Rajagopalan
  • 5,465
  • 2
  • 11
  • 29

1 Answers1

3

Use Module#const_get (assuming these classes are already defined in the global namespace):

%w|IndividualContact Legal|.map do |klazz|
  Kernel.const_get(klazz).new
end

The code above will return an array containing two instances: one instance of IndividualContact and one of Legal.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160