6

I need to do something like that

class Foo
 define perform()
  puts 'hello'
 end
end

classname = 'Foo'

instance = create_instance(classname)
instance.perform();

Is something like that possible. If is the how?

Thanks a lot!

0

3 Answers 3

7

You could use const_get:

instance = Object.const_get(classname).new
instance.perform
Sign up to request clarification or add additional context in comments.

Comments

4

You can use Module#const_get

klass = Object.const_get(classname)
instance = klass.new

But you might want to whitelist classname first if it's coming from user input. Otherwise you're potentially opening a security hole.

Comments

3

Yes, it's possible-

class Foo
  def perform
    puts 'hello'
  end
end

f = 'Foo'

klass = Object.const_get f

f.new.perform

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.