gpt4 book ai didi

Ruby 元编程 : adding @variables to existing 'initialize' method (using class_eval)

转载 作者:太空宇宙 更新时间:2023-11-03 16:06:26 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Ruby.Metaprogramming. class_eval

我有这个小项目,目标是创建一个“attr_accessor_with_history”方法,该方法将记录分配给它创建的变量的每个值。这是代码:

class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s # make sure it's a string
attr_reader attr_name # create the attribute's getter
attr_reader attr_name+"_history" # create bar_history getter

a = %Q{
def initialize
@#{attr_name}_history = [nil]
end

def #{attr_name}
@#{attr_name}
end

def #{attr_name}=(new_value)
@#{attr_name}=new_value
@#{attr_name}_history.push(new_value)
end }
puts a

class_eval(a)

end
end

现在,当我针对一个变量测试脚本时。它工作正常。但是当我尝试创建两个或更多变量时(像这样)....

class Foo
attr_accessor_with_history :bar
attr_accessor_with_history :lab
end

a = Foo.new
a.bar = 45
a.bar = 5
a.bar = 'taat'
puts a.bar_history

b = Foo.new
b.lab = 4
b.lab = 145
b.lab = 'tatu'
puts b.lab_history

....Ruby 给出了“(class_eval) bar_history.push(new_value) 的不存在的‘推送’方法”。我认为“初始化”方法在第二次调用 attr_accessor_with_history 时被覆盖,因此第一个变量的记录被销毁。

我不知道如何解决这个问题。我已经尝试过调用 'super' 。有什么线索吗?

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