请考虑以下代码:
module MyClass
def foo
"method"
end
end
现在,我可以像往常一样实例化一个新类
@my_new_class = MyClass.new
或者,我可以做一些元编程魔术
@my_new_class = Class.new { include MyClass }.send :new
问题是两者有什么区别?
最佳答案
上面的代码(几乎)等同于:
MyNewClass = Class.new { include MyClass }
@my_new_class = MyNewClass.new
这就像
class MyNewClass
include MyClass
end
@my_new_class = MyNewClass.new
使用 Class.new
即时声明一个匿名新类:
Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given). You can give a class a name by assigning the class object to a constant.
If a block is given, it is passed the class object, and the block is evaluated in the context of this class using
class_eval
.
关于ruby - 这个 Ruby 使用 Class.new 来创建类,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25389036/