Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class instance creating with class name in variable Ruby

Tags:

ruby

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!

like image 943
yety Avatar asked May 12 '12 23:05

yety


People also ask

How do you create an instance of a class in Ruby?

Defining a class in Ruby: Simply write class keyword followed by the name of the class. The first letter of the class name should be in capital letter.

How do you declare an instance variable in Ruby?

An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.

What is class instance variable in Ruby?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.

How do I use a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.


1 Answers

You could use const_get:

instance = Object.const_get(classname).new
instance.perform
like image 93
rjz Avatar answered Nov 15 '22 04:11

rjz