From: Robert Klemme Date: 2011-04-29T17:06:42+09:00 Subject: Re: Initialize Struct from Hash On Thu, Apr 28, 2011 at 10:50 PM, Joel VanderWerf wrote: > Tangentially, I wonder if anything like the following (very rough proof of > concept) has been used instead of Struct. > > class Hash >  def structify! >    keys.each do |key| >      class << self; self; end.class_eval do >        define_method key do >          fetch key >        end >        define_method "#{key}=" do |val| >          store key, val >        end >      end >    end >  end > end > > h = {:foo => 1, :bar => 2} > h.structify! > p h.foo # 1 > h.foo = 3 > p h.foo # 3 > p h     # {:foo=>3, :bar=>2} > p h.oof # undefined irb(main):004:0> h = {:foo => 1, :bar => 2} => {:foo=>1, :bar=>2} irb(main):005:0> o = OpenStruct.new(h) => # irb(main):006:0> o.foo => 1 irb(main):007:0> o.bar => 2 Well, here we differ irb(main):008:0> o.oof => nil But the issue with your approach is that it is not dynamic. Keys added or removed after call to #structify! will not be taken care of. A more dynamic approach would be module HashStruct def method_missing(s,*a,&b) case when a.empty? && key?(s) self[s] when a.size == 1 && /\A(.+)=\z/ =~ s self[$1.to_sym] = a.first else super end end end h.extend HashStruct h.foo Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/