From: benjohn@... Date: 2006-10-03T17:30:56+09:00 Subject: Re: Creating modules >> def initialize(a_constant_to_go_in_module) >> self.module_eval do >> K = a_constant_to_go_in_module >> def a_method; 'wibble'; end >> end >> end > > Ah! I think that's exactly what I want :) Thanks, I'll give it a try :) So, I've been having an experiment, and here's what I've found so far... irb(main):001:0> class MyModule < Module irb(main):002:1> def initialize(k) irb(main):003:2> module_eval {K=k} irb(main):004:2> end irb(main):005:1> end SyntaxError: compile error (irb):3: dynamic constant assignment module_eval {K=k} ^ from (irb):5 But I can do... irb(main):001:0> x=10 => 10 irb(main):002:0> m=Module.new => # irb(main):003:0> m.module_eval {K=x} => 10 However, if I then try... irb(main):004:0> m::K NameError: uninitialized constant #::K from (irb):4 irb(main):005:0> m.constants => [] But I can do... irb(main):006:0> m.const_get(:X) NameError: uninitialized constant #::X from (irb):6:in `const_get' from (irb):6 irb(main):007:0> m.const_get(:K) => 10 !? Huh? I guess this is something to do with constants being looked up in a global symbol pool? Going back to trying to define a sub class of modules... irb(main):009:0> vishnu in new_try# irb irb(main):001:0> class MyModule < Module irb(main):002:1> def initialize(x) irb(main):003:2> super() irb(main):004:2> module_eval do irb(main):005:3* def f; x; end irb(main):006:3> def self.g; x*x; end irb(main):007:3> end irb(main):008:2> end irb(main):009:1> end => nil irb(main):010:0> m=MyModule.new(10) => # irb(main):011:0> m.g NameError: undefined local variable or method `x' for # from (irb):6:in `g' from (irb):11 irb(main):012:0> Object.new.extend(m).f NameError: undefined local variable or method `x' for # from (irb):5:in `f' from (irb):12 irb(main):013:0> ...Which is a bit of a pitty. I also briefly dabled with... irb(main):018:0> class ParameterClass < Class irb(main):019:1> end TypeError: can't make subclass of Class from (irb):18 irb(main):020:0> And turned away from that avenue. I think I need a better idea of what is and isn't possible here. I think my understanding of the dark secrets is very little; I was hoping I'd get away with that though, as I generally have with Ruby until now :) Cheers, Benjohn