dav*_*k01 5 ruby metaprogramming dynamic-code
当涉及到运行时内省和动态代码生成时,我不认为ruby有任何竞争对手,除了可能的一些lisp方言.前几天我正在做一些代码练习来探索ruby的动态设施,我开始想知道如何向现有对象添加方法.以下是我能想到的三种方式:
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
Run Code Online (Sandbox Code Playgroud)
这是冰山的一角,因为我还没有探索的各种组合instance_eval
,module_eval
和define_method
.是否有在线/离线资源,我可以找到更多关于这种动态技巧的信息?