Heads up: This description was created by AI and might not be 100% accurate.
hash2class.rb
This Ruby code snippet demonstrates the use of Class.new to create a dynamic class based on a given hash object. The create_dynamic_class method takes a hash as an argument and returns a new class that has accessor methods for each key in the hash. The class also includes an initialize method that sets instance variables for each key-value pair in the hash.
The code first defines a hash object named data with three key-value pairs: name, age, and city. It then calls the create_dynamic_class method on the data hash to create a new dynamic class. The resulting class has accessor methods for name, age, and city, and an initialize method that sets instance variables for each key-value pair in the hash.
The code then creates an instance of the dynamically created class using the new keyword. It then prints the values of the name, age, and city attributes of the object to the console.
Ruby code snippet
data = { name: "Alice", age: 25, city: "Tokyo" }
#=> {name: "Alice", age: 25, city: "Tokyo"}
def create_dynamic_class(hash)
Class.new do
hash.each_key do |key|
attr_accessor key.to_sym
end
define_method(:initialize) do
hash.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
end
end
#=> :create_dynamic_class
kls = create_dynamic_class data
#=> #<Class:0x00007f876d3cc098>
obj = kls.new
#=>
#<#<Class:0x00007f876d3cc098>:0x00007f876d376530
obj
#=>
#<#<Class:0x00007f876d3cc098>:0x00007f876d376530
@age=25,
@city="Tokyo",
@name="Alice">
obj.name
#=> "Alice"
obj.age
#=> 25
obj.city
#=> "Tokyo"
Executed with Ruby 3.4.4
.