hash2class.rb(meta)
The Ruby code uses metaprogramming to create a dynamic class based on a hash. It defines a method create_dynamic_class that takes a hash and generates a new class. This class has attributes corresponding to the hash keys, with getter and setter methods, and an initializer that sets these attributes using the hash’s values. When you create an instance of this class, it automatically has the properties defined by the original hash (e.g., name, age, city).
Execution:
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:0x00007f9e618e0150>
obj = kls.new
#=>
#<#<Class:0x00007f9e618e0150>:0x00007f9e61997e90
obj
#=>
#<#<Class:0x00007f9e618e0150>:0x00007f9e61997e90
@age=25,
@city="Tokyo",
@name="Alice">
obj.name
#=> "Alice"
obj.age
#=> 25
obj.city
#=> "Tokyo"
Executed with Ruby 3.3.6