ruby - 这个 Ruby 使用 Class.new 来创建类,

标签 ruby metaprogramming

请考虑以下代码:

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/

相关文章:

ruby - 在 Ruby 中检测发音相似的词

ruby-on-rails - 是否有任何 Ruby gem 可以读取 .xls 和 .xlsx 文件?

ruby - 后缀数组并在字符串中搜索子串

ruby - FFMPEG:在带有可选音轨的视频上覆盖 PNG

ruby - 如何为 Ruby 中的所有实例设置默认(而不是 nil)变量初始化

f# - F# 引用有什么用吗?

ruby - 在哈希中访问哈希时如何处理潜在错误?

C++ 在编译时计算和排序 vector

c++ - 为什么我们不能直接使用类模板来推导方法模板?新加坡金融学会

django-models - Pythonic 字典遍历