Ask Your Question

Revision history [back]

The process of generating a class instance using a string name in Crystal involves the following steps:

  1. Get a reference to the class by using the 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")
  1. Create an instance of the class using the 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">