【发布时间】:2011-06-13 06:00:23
【问题描述】:
在运行时自省和动态代码生成方面,我认为 ruby 没有任何竞争对手,除了一些 lisp 方言。前几天我正在做一些代码练习来探索 ruby 的动态设施,我开始想知道如何向现有对象添加方法。以下是我能想到的 3 种方法:
obj = Object.new
# add a method directly
def obj.new_method
...
end
# add a method indirectly with the singleton class
class << obj
def new_method
...
end
end
# add a method by opening up the class
obj.class.class_eval do
def new_method
...
end
end
这只是冰山一角,因为我还没有探索过instance_eval、module_eval 和define_method 的各种组合。是否有在线/离线资源可以让我了解更多关于此类动态技巧的信息?
【问题讨论】:
标签: ruby metaprogramming dynamic-code