Dynamic Class Definition WITH a Class Name

前端 未结 4 1528
情深已故
情深已故 2020-12-04 10:47

How do I dynamically define a class in Ruby WITH a name?

I know how to create a class dynamically without a name using something li

4条回答
  •  抹茶落季
    2020-12-04 11:29

    The name of a class is simply the name of the first constant that refers to it.

    I.e. if I do myclass = Class.new and then MyClass = myclass, the name of the class will become MyClass. However I can't do MyClass = if I don't know the name of the class until runtime.

    So instead you can use Module#const_set, which dynamically sets the value of a const. Example:

    dynamic_name = "ClassName"
    Object.const_set(dynamic_name, Class.new { def method1() 42 end })
    ClassName.new.method1 #=> 42
    

提交回复
热议问题