Ruby 中 method_missing 和 const_missing 的使用与委托机制
1. const_missing 与 method_missing 的区别
在 Ruby 里, const_missing 和 method_missing 功能有相似之处。当 Ruby 检测到对未定义常量的引用时,就会调用 const_missing ;而当尝试调用不存在的方法时,会调用 method_missing 。不过,二者存在一些差异:
- 参数方面 : const_missing 仅接收一个参数,即包含缺失常量名称的符号。因为常量引用不像方法调用那样有参数。
- 方法类型方面 : const_missing 需为类方法。以下是一个示例:
class Document
def self.const_missing( const_name )
msg = %Q{
You tried to reference the constant #{const_name}
There is no such constant in the Document class.
}
raise msg
end
end
2. 实际应用案例
- Rai
超级会员免费看
订阅专栏 解锁全文
4

被折叠的 条评论
为什么被折叠?



