Ask Your Question
2

What is the process of generating a class instance using a string name in Crystal?

asked 2023-07-21 07:54:36 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-21 07:57:02 +0000

huitzilopochtli gravatar image

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">
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-21 07:54:36 +0000

Seen: 11 times

Last updated: Jul 21 '23