当谈到运行时自省(introspection)和动态代码生成时,我认为 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似乎是一个很好的资源。 (并且,从那里链接,The Book of Ruby。)
关于ruby - 可以通过多少种方法将方法添加到 ruby 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327114/