庇护祝福的分享

Be worthy

Ruby元编程五:编写代码的代码

Kernel#eval

kernel#eval会直接 执行字符串中的代码,并返回执行结果,和javascript中的eval()一样。

钩子方法

Class#inherited

当类被继承时,调用该方法,平时它什么也不做。,可以通过覆写它来形成类似回调函数的用法。 example:

class MyClass                         #inherited是Class的一个实例方法,对于一个特定的类,则是它的类方法。
    def self.inherited(param)         #注意inherited方法需要一个参数,参数是继承者的类名
        p "lala"
    end
end

MySonClass < MyClass; end       #=>"lala"

更多钩子方法

Class#inherited是最常用的,还有其他一些: Module#includeed Module#method_added Module#method_removed Module#method_undefined