Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.dougwise.org!nntpfeed.proxad.net!proxad.net!feeder1-2.proxad.net!usenet-fr.net!de-l.enfer-du-nord.net!feeder2.enfer-du-nord.net!talisker.lacave.net!lacave.net!not-for-mail From: Joel VanderWerf Newsgroups: comp.lang.ruby Subject: Re: Initialize Struct from Hash Date: Fri, 29 Apr 2011 10:27:49 -0500 Organization: Service de news de lacave.net Lines: 51 Message-ID: <4DBAD8F0.8000202@gmail.com> References: <919600ef40c16b10cb0f01a757234376@ruby-forum.com> <69c1ac462d5ff72621121fcf6c8135ec@ruby-forum.com> <4DB9D327.9000905@gmail.com> NNTP-Posting-Host: bristol.highgroove.com Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Trace: talisker.lacave.net 1304090895 96998 65.111.164.187 (29 Apr 2011 15:28:15 GMT) X-Complaints-To: abuse@lacave.net NNTP-Posting-Date: Fri, 29 Apr 2011 15:28:15 +0000 (UTC) In-Reply-To: X-Received-From: This message has been automatically forwarded from the ruby-talk mailing list by a gateway at comp.lang.ruby. If it is SPAM, it did not originate at comp.lang.ruby. Please report the original sender, and not us. Thanks! For more details about this gateway, please visit: http://blog.grayproductions.net/categories/the_gateway X-Mail-Count: 382387 X-Ml-Name: ruby-talk X-Rubymirror: Yes X-Ruby-Talk: <4DBAD8F0.8000202@gmail.com> Xref: x330-a1.tempe.blueboxinc.net comp.lang.ruby:3702 On 04/29/2011 01:06 AM, Robert Klemme wrote: > 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 That's intended: #structify is supposed to turn a hash into something that looks like a Struct, not an OpenStruct.