Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何使数组仅在第一次调用函数时初始化?_Ruby_Metaprogramming_Class Eval - Fatal编程技术网

Ruby 如何使数组仅在第一次调用函数时初始化?

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

我想制作一个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                                                                                                                          
    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"} ||= []