簡體   English   中英

如何在第一次調用函數時使數組初始化?

[英]How to make the array initialize only the first time function is called?

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訪問器,它會記錄數組中所有寫入的歷史記錄,但問題是在class_eval中,每次都會初始化數組,因此它不會保留舊值。

我應該做些什么改變?

使用||=

@#{attr_name+"_history"} ||= []

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM