From: "Jesús Gabriel y Galán" Date: 2011-04-29T02:10:18+09:00 Subject: Re: Initialize Struct from Hash 2011/4/28 Jesús Gabriel y Galán : > On Thu, Apr 28, 2011 at 7:00 PM, Brian Candler wrote: >> 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 = Struct.new :foo, :bar >> >> module FixStruct >>  def set(h) >>    h.each { |k,v| self[k] = v } >>    self >>  end >> end >> >> class K1 >>  include FixStruct >> end >> >> k1 = K1.new.set(:bar=>456, :foo=>123) >> p k1 >> >> (I'm talking about real Struct here, not OpenStruct etc) > > ruby-1.8.7-p334 :001 > K = Struct.new :id,:timestamp >  => K > ruby-1.8.7-p334 :002 > K[3,8] >  => # 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.