From: Jamie Quint Date: 2010-06-19T05:08:45+09:00 Subject: Accessing Class Variables in mixed in define_method I am using define_method inside a module to dynamically create a class after the module is mixed in. The module is writing out class variables for the class it is mixed into (yes I am aware that class variables are generally frowned upon but they are necessary in this instance) and then subsequently trying to access them through the method being created with define_method. The problem here is that define method is not able to access the class variables through class_variable_get or through accessing them directly. In the first case it fails because 'class_variable_get' is not a method on the class (oMethodError: undefined method ‘class_variable_get’ for #) In the second instance it fails because it thinks the class variable is uninitialized (NameError: uninitialized class variable @@c in M) It seems to be evaluating the '@@c' call in the context of the module and the class_variable_get call in the context of the class in which define_method is being called after it is mixed in. Does anyone know how I can get at the class variable here in define_method? Sample code below: Best, Jamie module M def cv(methodname) if class_variable_defined?(:@@c) classvar = class_variable_get(:@@c) classvar[rand(10000)] = "random" class_variable_set(:@cc,classvar) else class_variable_set(:@@c,{}) end define_method(methodname.to_sym) do # need to be able to get class variables for this class # @@c does not work because it tries to get the variable for the module and it exists only in the class #class_variable_get(:@@c) #does not work because its an invalid class method #@cc and class_variable_get(:@@c) are getting evaluated in different contexts which is strange end end end class Foo extend M cv("mfoo") end f = Foo.new f.mfoo # want this to be able to access and operate on class variables -- Posted via http://www.ruby-forum.com/.