【问题标题】:In how many ways can methods be added to a ruby object?有多少种方法可以添加到 ruby​​ 对象中?
【发布时间】: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_evalmodule_evaldefine_method 的各种组合。是否有在线/离线资源可以让我了解更多关于此类动态技巧的信息?

【问题讨论】:

    标签: ruby metaprogramming dynamic-code


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      此外,虽然这并不是您所要求的,但您可以轻松地给人一种通过使用 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
      

      【讨论】:

        【解决方案3】:

        我喜欢这本书Metaprogramming Ruby,它是由镐书的出版商出版的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-23
          • 1970-01-01
          相关资源
          最近更新 更多