有多少种方法可以添加到ruby对象?

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_evaldefine_method.是否有在线/离线资源,我可以找到更多关于这种动态技巧的信息?

jtb*_*des 4

Ruby Metaprogramming似乎是一个很好的资源。(并且,从那里链接到《红宝石之书》。)