From: dblack@... Date: 2003-08-12T07:54:37+09:00 Subject: Re: newbie mixin questions Hi -- On Tue, 12 Aug 2003, Michael Garriss wrote: > Gennady wrote: > > >----- Original Message ----- > >From: "Michael Garriss" > >To: "ruby-talk ML" > >Sent: Monday, August 11, 2003 3:16 PM > >Subject: newbie mixin questions > > > > > > > > > >>Hi, > >> Just 2 questions: > >> > >>1) How can I mixin a class method (not an instance method)? > >> > >> > > > >class A > > class << self > > include SomeModule > > end > >end > > > > > Very cool. Will this require me to have two seperate modules though? > One for including class methods and the other of including the instance > methods. No, modules are very modular and can fit almost anywhere :-) Here's a little illustration of how and why this works. Step 1: create a module module SomeModule def talk puts "hi" end end and include it in a class in the usual way: class A include SomeModule end Now all instances of A can talk: A.new.talk # hi Now, by way of parallel example: instead of class A, do the same thing with class Class: class Class include SomeModule end Now all instances of Class can talk: A.talk # hi String.talk # hi Class.new.talk # hi That, by the way, is the heart of class methods: essentially, adding instance methods to objects which are instances of Class. The only problem is that you probably don't want all Class objects to talk; you only want A to talk. So actually, instead of the above, you can do what Gennady did, which restricts the addition of 'talk' to just the one Class object (A): class A class << self # operating just on A's singleton class, include SomeModule # so only A will gain the ability to talk end end A.talk # hi String.talk # error! only added 'talk' capability to A David -- David Alan Black home: dblack@superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav