From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2003-01-22T18:00:03+09:00 Subject: Re: accessors for module instance vars In article , ahoward wrote: >On 22 Jan 2003, Phil Tomson wrote: > >> That's certianly one way to do it... I guess I'm looking at Evolvable as >> more of a namespace than a class that defines an object, though. > >a singleton is really nothing more than an encapsulation of some data and some >methods - just like a namespace - but i understand your objection > >> And if I leave it as a module it could be mixed into a class later (though >> that's not how I'm using it now) and all of the 'module instance variables' >> would also end up in the class it was mixed into.... > >i don't think it works that way : > > module M > attr_accessor :x > @x = 42 > end > > class Foo; include M; end > > p Foo.new.x # >> nil > >the instance variable STAY in M, that's what i was referring to when i said i >was unsure of the semantics. this works: module M def x if not defined? @x @x = 0 end @x end def x=(x) @x=x end end class Foo; include M; end Foo.new.x #-> 0 However, those are instance methods (x and x=) defined in module M and since M can't be instantiated they are only callable after M is mixed into a class and an instance of that class is created. I wonder if there is a way to mixin module methods so that they become instance methods of a class? module M def M.x if not defined? @x @x=0 end @x end end class MyM include_module_methods_of M #somehow end MyM.new.x #-> 0 Anyone know of a way to do this? (I have no pressing need for this, just curious) Phil -- "Or perhaps the truth is less interesting than the facts?" Amy Weiss (accusing theregister.co.uk of engaging in 'tabloid journalism') Senior VP, Communications Recording Industry Association of America