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
我得到: undefined method 'basename' for class 'File' (NameError)
顺便说一下,我正在使用JRuby
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
class << self
评估“类级别”(Eigenklass)上的所有内容 - 因此您不需要编写self.
( def self.basename
)和alias_method
适用于类方法。
class << File alias_method :old_bn, :basename def basename(f) puts "herro wolrd!" old_bn(*args) end end