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

Ruby-如何重新定义类方法?,ruby,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 我得到:类“File”(namererror)的未定义方法“basename” 顺便说一句,我使用的是JRubyalias\

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

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

这不起作用:

class File
  alias_method :old_bn, :basename

  def basename(*args)
    puts "herro wolrd!"
    old_bn(*args)
  end
end
我得到
:类“File”(namererror)的未定义方法“basename”


顺便说一句,我使用的是JRuby
alias\u方法
是指实例方法。但是
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
类文件

class
class个人偏好。如果我使用monkey patch,我倾向于在我的
core\u ext
中搜索
类文件
,并希望在那里找到所有修改。而且,用谷歌搜索
类也更容易
class << File
  alias_method :old_bn, :basename
  def basename(f)
    puts "herro wolrd!"
    old_bn(*args)
  end
end