在运行时创建一个类如下:
klass = Class.new superclass, &block
Object.const_set class_name, klass
例子:
class Person
def name
"Jon"
end
end
klass = Class.new Person do
def name
"#{super} Doe"
end
end
Object.const_set "Employee", klass
puts Employee.new.name # prints "Jon Doe"
现在,假设您有一个名为 Company 的模块:
module Company
end
如何在运行时在 Company 模块/命名空间中创建 Employee 类,以便以下产生相同的结果?
puts Company::Employee.new.name # prints "Jon Doe"