From: Quintus Date: 2012-05-09T20:45:00+09:00 Subject: Re: How to make a given klass to include a module Am 09.05.2012 13:36, schrieb I��aki Baz Castillo: > Hi, simple code: > > ---------------------------- > module M > def hello > "HELLO" > end > end > > class A > end > > > klass = A > ---------------------------- > > Now I want to make an instance of klass (so an instance of A) but also > need that klass includes module M. > Note however that I cannot change class A definition since klass is > given in runtime by the user. > > NOTE: It must be efficient, I don't want to use eval and so. > > Thanks a lot. > > # ruby -v: ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux] irb(main):001:0> module M irb(main):002:1> def hello irb(main):003:2> "HELLO" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> class A irb(main):007:1> end => nil irb(main):008:0> klass = A => A irb(main):009:0> klass.send(:include, M) => A irb(main):010:0> a = klass.new => # irb(main):011:0> a.hello => "HELLO" Alternatively, if you don���t want to pollute the given class, use #extend on the instances (which is also more clean as it doesn���t require #send). Vale, Marvin