ruby - Access global class variable in the anonymous function -


i'm trying use self.instance_exec method. instance variable @legend in case gets printed nicely, class variable throws error:

uninitialized class variable @@holiday_legend_counter in object (nameerror) 

my example code:

class calender    def initialize(options)      @@holiday_legend_counter = "a"      @legend = 'a'    end     def print_date(print_date)      # calculation calculate date , current date        self.instance_exec date, @current_start_date, &print_date    end end    print_legend = proc.new |date,current_date|   print @@holiday_legend_counter   print @legend end  cal = calender.new cal.print_date(print_legend) 

what might want can achieved modifying above code below. note when want use class level global variable, it's best use instance variable of singleton class. has advantage don't accidentally override @@holiday_legend_counter value in sub class thereby changing super class's value @@holiday_legend_counter because @@holiday_legend_counter shared across class hierarchy.

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 calculate date , current date     self.instance_exec  @current_start_date, &print_date   end  end   print_legend = proc.new |date, current_date|  print calender.holiday_legend_counter  print @legend end  cal = calender.new("") cal.print_date(print_legend) 

class level instance variables provide better approach when need store class level values (not global or instance level)


Comments