5

在运行时自省和动态代码生成方面,我认为 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。是否有在线/离线资源,我可以在其中找到有关此类动态技巧的更多信息?

4

3 回答 3

4

Ruby Metaprogramming似乎是一个很好的资源。(并且,从那里链接到The Book of Ruby。)

于 2011-06-13T06:59:26.060 回答
3

如果有一个超类,您可以使用您提到的(API)从超类obj添加方法。如果您查看过 Rails 源代码,您会注意到他们经常这样做。objdefine_method

此外,虽然这不是您所要求的,但您可以轻松地给人一种通过使用动态创建几乎无限数量的方法的印象method_missing

def method_missing(name, *args)
  string_name = name.to_s
  return super unless string_name =~ /^expected_\w+/
  # otherwise do something as if you have a method called expected_name
end

将它添加到您的类将允许它响应任何看起来像的方法调用

@instance.expected_something
于 2011-06-13T08:24:33.297 回答
2

我喜欢由pickaxe书的出版商出版的Metaprogramming Ruby一书。

于 2011-06-14T00:58:59.643 回答