0

我正在嘗試使用self.instance_exec方法。在我的案件實例變量@legend會打印非常漂亮,但類變量拋出一個錯誤:在匿名函數中訪問全局類變量

uninitialized class variable @@holiday_legend_counter in Object (NameError) 

我的示例代碼:

class Calender 
    def initialize(options) 
    @@holiday_legend_counter = "a" 
    @legend = 'A' 
    end 

    def print_date(print_date) 
    # some calculation to calculate date and the current date 
    self.instance_exec date, @current_start_date, &print_date 
    end 
end 


print_legend = Proc.new do |date,current_date| 
    print @@holiday_legend_counter 
    print @legend 
end 

cal = Calender.new 
cal.print_date(print_legend) 

回答

0

你可能想什麼可以通過稍微修改上面的代碼來實現如下所示。請注意,當您想要使用類級別的全局變量時,最好將其用作Singleton類的實例變量。這樣做的好處是,您不會無意中覆蓋子類中的@@ holiday_legend_counter值,從而更改@@ holiday_legend_counter的超類值,因爲@@ holiday_legend_counter是通過類層次結構共享的。

class Calender 

    @holiday_legend_counter = "a" 
    class << self;attr_reader :holiday_legend_counter end 


    def initialize(options) 
    @legend = 'A' 
    end 

    def print_date(print_date) 
    #somecalculation to calculate date and the current date 
    self.instance_exec @current_start_date, &print_date 
    end 
end 

print_legend = Proc.new do |date, current_date| 
print Calender.holiday_legend_counter 
print @legend 
end 

cal = Calender.new("") 
cal.print_date(print_legend) 

類級別的實例變量提供更好的方法,當你需要存儲類的電平值(不是全局或實例級別)