Ruby - 如何重新定义类方法?

Rub*_*osa 11 ruby

如何在ruby中重新定义类方法?

比方说,例如,我想重新定义方法File.basename("C:\abc.txt")我该怎么做?

这不起作用:

class File
  alias_method :old_bn, :basename

  def basename(*args)
    puts "herro wolrd!"
    old_bn(*args)
  end
end
Run Code Online (Sandbox Code Playgroud)

我明白了 : undefined method 'basename' for class 'File' (NameError)

顺便说一下,我正在使用 JRuby

Mar*_*rth 18

alias_method例如,方法.但是File.basename是一种类方法.

class File
  class << self
    alias_method :basename_without_hello, :basename

    def basename(*args)
      puts "hello world!"
      basename_without_hello(*args)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

class << self评估关于"一流水平"(Eigenklass)的一切-这样你就不需要写self.(def self.basename),并alias_method适用于类的方法.

  • 个人喜好.如果我猴子补丁我倾向于在我的`core_ext`中搜索`class File`并想在那里找到所有的修改.此外,它更容易谷歌`class << self`并找出这意味着如果新人开始研究该代码并且还没有看到那个成语. (4认同)