gpt4 book ai didi

ruby - 在 Ruby 中覆盖 attr_* 方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:42:35 24 4
gpt4 key购买 nike

我正在读这本书“The Well-Grounded Rubyist”,我突然想到了这个问题。我知道在 Ruby 中可以重新打开一个类并覆盖该方法。

例子:

class A
def x
"First definition of x"
end

def x
"Second definition of x"
end
end

test = A.new
test.x #returns "Second definition of x"

根据以上结果,我很好奇是否可以用我自己的(随机)定义覆盖类方法 attr_accessor。这是我的想法:

class Dummy
attr_accessor :test

def self.attr_accessor(method_name)
puts "Overwrite the default functionality of attr_accessor by printing this text instead."
end
end

d = Dummy.new
d.test #not sure why this returns nil instead of putting my message
Dummy.attr_accessor(test) #fails because of ArgumentError: wrong number of arguments (0 for 2..3)

对于上面的两个例子,我希望通过修改和提问来获得你的洞察力,从而更好地理解 Ruby。

最佳答案

您走在正确的道路上,但类定义在运行时按顺序执行。您需要在调用新方法之前定义它,否则原始方法将用于该方法。

如果你这样做

class Dummy
def self.attr_accessor(method)
puts 'your message here'
end
attr_accessor :test # message printed
end

d = Dummy.new
d.test # raises an error, since we aren't creating a test method anymore
Dummy.attr_accessor(test) #will still fail, read on

test是Ruby中的一个方法,对应shell中的test。该方法就是为什么您最后会收到错误的原因。你真正想要的是

Dummy.attr_accessor(:test1)

请注意,您将无法调用普通的 attr_accessor,因为它是类实例上的私有(private)方法,即类定义中的 self。 (IOW,attr_accessorModule 上的私有(private)实例方法,在执行类定义时,selfModule 的实例)

关于ruby - 在 Ruby 中覆盖 attr_* 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554964/

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