Heads up: This description was created by AI and might not be 100% accurate.
hash2class.rb
This Ruby code snippet demonstrates a dynamic class creation. It defines a create_dynamic_class
function that generates a class based on a provided hash. This class automatically creates instance variables for each key in the hash, allowing you to define and access attributes dynamically based on the hash’s content, and then creates an instance of this class and sets its attributes.
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:0x00007fc3601380c8>
obj = kls.new
#=>
#<#<Class:0x00007fc3601380c8>:0x00007fc3600c1680
obj
#=>
#<#<Class:0x00007fc3601380c8>:0x00007fc3600c1680
@age=25,
@city="Tokyo",
@name="Alice">
obj.name
#=> "Alice"
obj.age
#=> 25
obj.city
#=> "Tokyo"
Executed with Ruby 3.4.5
.