如何在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
适用于类的方法.
归档时间: |
|
查看次数: |
12025 次 |
最近记录: |