Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection in Ruby. Instantiate an object by given class name

I came to ruby from PHP. How could i do the next thing in ruby?

$className = 'ArrayObject';
$arrayObject = new $className();
like image 322
vooD Avatar asked Mar 31 '10 20:03

vooD


People also ask

What is instantiation of a class in Ruby?

An object instance is created from a class through the process called instantiation. In Ruby this takes place through the Class method new . Example: anObject = MyClass. new(parameters)

Does Ruby support reflection?

We've seen that Ruby is a very dynamic language; you can insert new methods into classes at runtime, create aliases for existing methods, and even define methods on individual objects. In addition, it has a rich API for reflection.

What is object in Ruby on Rails?

Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.

What does object mean in Ruby?

Object: That's just any piece of data. Like the number 3 or the string 'hello'. Class: Ruby separates everything into classes. Like integers, floats and strings. Method: These are the things that you can do with an object.


3 Answers

You can do this:

arrayObject = Object::const_get('Array').new
like image 130
John Topley Avatar answered Oct 03 '22 20:10

John Topley


You can also use the following if you are using Ruby on Rails:

array_object = "Array".constantize.new
like image 21
Randy Simon Avatar answered Oct 03 '22 21:10

Randy Simon


If you have a class, like for example String:

a = String
a.new("Geo")

would give you a string. The same thing applies to other classes ( number & type of parameters will differ of course ).

like image 22
Geo Avatar answered Oct 03 '22 20:10

Geo