1 | initial version |
The process of generating a class instance using a string name in Crystal involves the following steps:
Object.const_get
method which takes the class name as a string and returns the class object.For example, if the name of the class is "Person"
class Person
def initialize(name)
@name = name
end
end
you can obtain a reference to it using:
clazz = Object.const_get("Person")
new
method on the class object.person = clazz.new("John")
This will create an instance of the Person
class with the name "John".
The complete code:
class Person
def initialize(name)
@name = name
end
end
clazz = Object.const_get("Person")
person = clazz.new("John")
puts person # => #<Person:0x7fc6fe831520 @name="John">