2011/4/28 Jes=FAs Gabriel y Gal=E1n <jgabrielygalan / gmail.com>:
> On Thu, Apr 28, 2011 at 7:00 PM, Brian Candler <b.candler / pobox.com> wrot=
e:
>> I just want to check I've not missed something here. Is there a built-in
>> way to initialize a Struct from a hash of key/value pairs?
>>
>> That is, can I shorten the following?
>>
>> K1 =3D Struct.new :foo, :bar
>>
>> module FixStruct
>> =A0def set(h)
>> =A0 =A0h.each { |k,v| self[k] =3D v }
>> =A0 =A0self
>> =A0end
>> end
>>
>> class K1
>> =A0include FixStruct
>> end
>>
>> k1 =3D K1.new.set(:bar=3D>456, :foo=3D>123)
>> p k1
>>
>> (I'm talking about real Struct here, not OpenStruct etc)
>
> ruby-1.8.7-p334 :001 > K =3D Struct.new :id,:timestamp
> =A0=3D> K
> ruby-1.8.7-p334 :002 > K[3,8]
> =A0=3D> #<struct K id=3D3, timestamp=3D8>

Sorry, I just realized this is not what you want.
Although if you know the order of the attributes defined by the
Struct, you can build something upon this, transforming the hash into
an array in the appropriate order. Whether that's cleaner than your
solution is not so clear.

Jesus.