Convert a String to a Constant in Ruby

Below are the possible approaches to convert a string to a constant in Ruby.

Approach 1: Using Object.const_set

  1. In this approach, we are using Object.const_set to dynamically create a new constant named β€œHelloGFG” by converting the string β€œHelloGFG” into a class using Class.new.
  2. This allows us to instantiate objects of this class and access its properties and methods using the constant name β€œHelloGFG” in Ruby code.

In the below example, Object.const_set is used to convert a string to a constant in Ruby.

Ruby
# Define a string
str = "HelloGFG"

# Convert string to constant
Object.const_set(str, Class.new)

# Now we can use the constant
puts HelloGFG.new.inspect

Output:

Approach 2: Using const_missing hook

  1. In this approach, we are utilizing the const_missing hook to dynamically create a constant named β€œGFG” by defining it as a class using Class.new if it is not already defined.
  2. This makes sure that the constant β€œGFG” is available for instantiation and usage in the Ruby code.

In the below example, const_missing hook is used to convert a string to a constant in Ruby.

Ruby
# Define a string
str = "GFG"

# Implement const_missing hook to handle constant creation
Object.const_set(:GFG, Class.new) unless Object.const_defined?(:MyDynamicClass)

# Now we can use the constant
puts GFG.new.inspect

Output:

Approach 3: Using eval

  1. In this approach, we are using eval to dynamically convert the string β€œHelloGFG” into a constant by creating a new class using Class.new and assigning it to the evaluated string β€œ#{str}β€œ.
  2. This allows us to instantiate objects of the class and access its properties and methods using the constant name β€œHelloGFG” in Ruby code.

In the below example, eval is used to convert a string to a constant in Ruby.

Ruby
# Define a string
str = "HelloGFG"

# Convert string to constant using eval
eval("#{str} = Class.new")

# Now we can use the constant
puts HelloGFG.new.inspect

Output:


How to convert a string to a constant in Ruby?

In this article, we will learn how to convert a string to a constant in Ruby. Conversion of string to constant consists of dynamically defining a new class or module using the string’s value as the constant name, allowing for runtime creation and usage of the constant in Ruby code.

Similar Reads

Convert a String to a Constant in Ruby

Below are the possible approaches to convert a string to a constant in Ruby....