Heads up: This description was created by AI and might not be 100% accurate.
hash2class.rb
This Ruby code snippet demonstrates dynamic class creation. It takes a hash (data
) and creates a new class whose attributes are dynamically defined based on the hash keys. The create_dynamic_class
method defines accessors (using attr_accessor
) and an initialize
method to set instance variables corresponding to the hash keys and values. An instance of the dynamically created class (obj
) is then created and its attributes can be accessed like any other object’s attributes (e.g., obj.name
, obj.age
).
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:0x00007fa35ae77818>
obj = kls.new
#=>
#<#<Class:0x00007fa35ae77818>:0x00007fa35adf1380
obj
#=>
#<#<Class:0x00007fa35ae77818>:0x00007fa35adf1380
@age=25,
@city="Tokyo",
@name="Alice">
obj.name
#=> "Alice"
obj.age
#=> 25
obj.city
#=> "Tokyo"
Executed with Ruby 3.4.5
.