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 o=
f
> concept) has been used instead of Struct.
>
> class Hash
> =A0def structify!
> =A0 =A0keys.each do |key|
> =A0 =A0 =A0class << self; self; end.class_eval do
> =A0 =A0 =A0 =A0define_method key do
> =A0 =A0 =A0 =A0 =A0fetch key
> =A0 =A0 =A0 =A0end
> =A0 =A0 =A0 =A0define_method "#{key}=3D" do |val|
> =A0 =A0 =A0 =A0 =A0store key, val
> =A0 =A0 =A0 =A0end
> =A0 =A0 =A0end
> =A0 =A0end
> =A0end
> end
>
> h =3D {:foo =3D> 1, :bar =3D> 2}
> h.structify!
> p h.foo # 1
> h.foo =3D 3
> p h.foo # 3
> p h =A0 =A0 # {:foo=3D>3, :bar=3D>2}
> p h.oof # undefined

irb(main):004:0> h =3D {:foo =3D> 1, :bar =3D> 2}
=3D> {:foo=3D>1, :bar=3D>2}
irb(main):005:0> o =3D OpenStruct.new(h)
=3D> #<OpenStruct foo=3D1, bar=3D2>
irb(main):006:0> o.foo
=3D> 1
irb(main):007:0> o.bar
=3D> 2

Well, here we differ

irb(main):008:0> o.oof
=3D> 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 =3D=3D 1 && /\A(.+)=3D\z/ =3D~ s
      self[$1.to_sym] =3D a.first
    else
      super
    end
  end
end

h.extend HashStruct
h.foo

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/