From: Rick DeNatale Date: 2008-02-13T06:19:03+09:00 Subject: Re: How to add a instance variable through a mixin? On 2/12/08, MrBanabas@googlemail.com wrote: > Hi, > > I would like to have a mixin which adds an instance variable to a > class. I ve tried it the following way: > > I ve defined a little module: > module MyApp > module MyMixin > def self.included(base) > @should_be_an_instance_variable = nil > end > end > end > > which is included by my little class: > class MyClass > include MyApp::MyMixin > end > > However, it seems that @should_be_an_instance_variable is currently > defined per mixin, but I would like to have a unique one for each > object of MyClass. You don't really add instance variables for the instances of classes to classes in Ruby. http://talklikeaduck.denhaven2.com/articles/2008/02/08/whose-variable-is-it-anyway If you add a method to a class through a mixin which refers to an instance variable, the variable will be created dynamically in the instance as needed when the method is run. if you want to initialize it to something other than nil, you can use techniques like lazy initialization. module M def iv @iv ||= 0 # or whatever you want the default value to be end end -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/