From: ahoward Date: 2003-01-22T05:38:05+09:00 Subject: Re: accessors for module instance vars On 21 Jan 2003, Phil Tomson wrote: > I've got a module that that has several classes defined within it. These > classes need to access some instance variables defined at the module > level. > > For example: > > module Evolvable > PC = 0.2 > PM = 0.01 > end > > Now this works ok, but I'm wondering if there's a way to create the > accessor methods for the Evolvable module automatically like with > attr_accessor and attr_reader. The problem with attr_accessor is that it > creates an instance method, not a module method - is there a way to > automatically create a module method? i'm unsure of the semantics of instance variables in a module (something you cannot declare an instance of) but assuming you need both the module defaults AND 'instance variable' in your module (perhaps because you will want to tweak these 'instance variables' later and yet have sensible defaults) why not simply : class Evolvable require 'singleton' include Singleton private PC = 0.2 def initialize @pc = PC end attr_writer :pc public attr_reader :pc end e = Evolvable.instance puts e.pc # >> 0.2 perhaps PC should be @@pc or something, but you get the picture : by putting the vars in a class you can use attr_*, but making the class a Singleton you ensure only one copy of @pc will ever exist. -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ahoward@fsl.noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 ====================================