gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:19 25 4
gpt4 key购买 nike

如何在 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适用于类方法。

关于Ruby - 如何重新定义类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5389125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com