Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #3702
| From | Joel VanderWerf <joelvanderwerf@gmail.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Initialize Struct from Hash |
| Date | 2011-04-29 10:27 -0500 |
| Organization | Service de news de lacave.net |
| Message-ID | <4DBAD8F0.8000202@gmail.com> (permalink) |
| References | <919600ef40c16b10cb0f01a757234376@ruby-forum.com> <69c1ac462d5ff72621121fcf6c8135ec@ruby-forum.com> <4DB9D327.9000905@gmail.com> <BANLkTikR=wRKtkfe46=j+apo9bLRR-CHgQ@mail.gmail.com> |
On 04/29/2011 01:06 AM, Robert Klemme wrote:
> On Thu, Apr 28, 2011 at 10:50 PM, Joel VanderWerf
> <joelvanderwerf@gmail.com> 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)
> => #<OpenStruct foo=1, bar=2>
> 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.
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Initialize Struct from Hash Brian Candler <b.candler@pobox.com> - 2011-04-28 12:00 -0500
Re: Initialize Struct from Hash Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-28 12:05 -0500
Re: Initialize Struct from Hash Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-28 12:10 -0500
Re: Initialize Struct from Hash 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-28 12:16 -0500
Re: Initialize Struct from Hash Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-28 12:19 -0500
Re: Initialize Struct from Hash Brian Candler <b.candler@pobox.com> - 2011-04-28 15:24 -0500
Re: Initialize Struct from Hash Joel VanderWerf <joelvanderwerf@gmail.com> - 2011-04-28 15:50 -0500
Re: Initialize Struct from Hash Robert Klemme <shortcutter@googlemail.com> - 2011-04-29 03:06 -0500
Re: Initialize Struct from Hash Joel VanderWerf <joelvanderwerf@gmail.com> - 2011-04-29 10:27 -0500
Re: Initialize Struct from Hash Brian Candler <b.candler@pobox.com> - 2011-04-29 03:22 -0500
csiph-web