【问题标题】:Ruby: Monkey patching String classRuby:猴子修补字符串类
【发布时间】:2012-10-13 18:30:36
【问题描述】:

我有点困惑为什么下面这段代码真的有效:

String.instance_eval do # self is set to String
  [:readlink, :symlink?, :expand_path].each do |method| # self is still String
    define_method(method) do # self is still String
      File.send(method, self) # what exactly is this self?
    end
  end
end
"asdf".expand_path # => "C:/users/some_user/asdf"

我不明白为什么最后一行会这样。定义每个方法时,方法的主体不等于File.send(method, String)吗?上述块实际上都没有改变self。唯一更改self 的行是String.instance_eval,它将self 更改为String

【问题讨论】:

    标签: ruby metaprogramming monkeypatching


    【解决方案1】:
    File.send(method, self)
    

    将在调用动态生成的方法时评估此self。那时它将被设置为 String 的一个实例。 (在您的示例中为“asdf”)。

    其实相当于打开String类,手动写所有这些方法。

    class String
      def readlink
        File.send :readlink, self
      end
    
      def expand_path
        File.send :expand_path, self
      end
    end
    

    【讨论】:

    • 好的,我的理解是,块在定义时会关闭所有变量。我将self 放入了那个变量桶中,但显然它具有更动态的性质。
    猜你喜欢
    • 2019-03-29
    • 2016-10-30
    • 2021-12-20
    • 2020-08-09
    • 1970-01-01
    • 2012-05-07
    • 2011-04-25
    • 2014-03-05
    • 2012-03-13
    相关资源
    最近更新 更多