I came to ruby from PHP. How could i do the next thing in ruby?
$className = 'ArrayObject';
$arrayObject = new $className();
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)
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.
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.
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.
You can do this:
arrayObject = Object::const_get('Array').new
You can also use the following if you are using Ruby on Rails:
array_object = "Array".constantize.new
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 ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With