Ruby 如何使数组仅在第一次调用函数时初始化?
我想制作一个attr访问器,它将记录数组中所有写入操作的历史记录,但问题是在类\u eval中,数组每次都被初始化,因此它不保存旧值 我应该做哪些更改?使用:Ruby 如何使数组仅在第一次调用函数时初始化?,ruby,metaprogramming,class-eval,Ruby,Metaprogramming,Class Eval,我想制作一个attr访问器,它将记录数组中所有写入操作的历史记录,但问题是在类\u eval中,数组每次都被初始化,因此它不保存旧值 我应该做哪些更改?使用: 这可能不是很明显,但第一行的|是一个链接:)。Saas课程非常受欢迎,非常酷 class Class def attr_accessor_with_history(attr_name) attr_name = attr_name.to_s # make sure it's a string
这可能不是很明显,但第一行的
|
是一个链接:)
。Saas课程非常受欢迎,非常酷
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
attr_reader attr_name+"_history" # create bar_history
class_eval %Q{
def #{attr_name}=(val)
@#{attr_name+"_history"}=[]
@#{attr_name+"_history"}.push(val)
@#{attr_name}=val
end
}
end
end
class Foo
attr_accessor_with_history :bar
end
@#{attr_name+"_history"} ||= []