On 15.06.2007 16:44, Trans wrote: > It's not uncommon to see initialize method take a hash or a setting > proc and apply that to accessors. Eg. > > def initialize( settings ) > settings.each{|k,v| send("{#k}=",v) > end > > or > > def initialize( &settings ) > settings.call(self) > end > > Today I come up with another potential approach: > > class Hash > def to_module(module_function=false) > m = Module.new > each do |k,v| > m.send(:define_method, k){ v } > m.send(:module_function, k) if module_function > end > return m > end > end > > M = { :a => 1 }.to_module(true) > p M.a #=> 1 > > > class Foo > def initialize( settings ) > extend settings.to_module > end > end > > f = Foo.new(:x => 9) > p f.x #=> 9 > > > Thoughts? irb(main):001:0> require 'ostruct' => true irb(main):002:0> f = OpenStruct.new(:x => 9) => #<OpenStruct x=9> irb(main):003:0> f.x => 9 :-) robert