I would often like a Hash to act like a Struct (or really, an object). That is, I might have a hash where: ''alpha'' => ''a'' ''beta'' => ''b'' I''d like to treat the hash as an object (obj) where: obj.send(''alpha'') == ''a'' and perhaps obj.beta == ''b'' Is there some built in way to do this? As for why this is relevant to Rails: many of the helpers (such as collection_select) can do a lot of magic for me, but only if I feed them a properly formatted instance variable with methods for getting the value and text of each option. I often find myself resorting to Structs for this data, but I wonder if there is a better way of thinking about this. (Aside from this question, if I''m falling into some Very Bad design pattern here, I''d love the advice.) d
Dev Purkayastha wrote:> I would often like a Hash to act like a Struct (or really, an object). > That is, I might have a hash where: > > ''alpha'' => ''a'' > ''beta'' => ''b'' > > I''d like to treat the hash as an object (obj) where: > > obj.send(''alpha'') == ''a'' > > and perhaps > > obj.beta == ''b'' > > Is there some built in way to do this?You can do this: require ''ostruct'' ostruct = OpenStruct.new("foo" => 5, "bar" => 42) ostruct.foo # => 5 ostruct.bar # => 42 or this: hash = { "foo" => "oof", "bar" => "rab" } OpenStruct.new(hash)
On Thursday 05 May 2005 08:48, Dev Purkayastha wrote:> I would often like a Hash to act like a Struct (or really, an > object)....> Is there some built in way to do this?See http://rubyurl.com/Eg157 for OpenStruct documentation. OpenStruct class also gives accessors to attributes. I hope that helps -- sdmitry -=- Dmitry V. Sabanin http://muravey.net