Posted By

noah on 06/08/09


Tagged

data object filter hash struct structure


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

webstic
4rp70x1n


to_struct method for Ruby hashes


 / Published in: Ruby
 

URL: http://rubyforge.org/snippet/detail.php?type=snippet&id=1

A very useful snippet found in this thread.

However it does not do deep conversion, that is, for a hash of hashes, you will get back a struct of hashes.

  1. class Hash
  2. def to_struct
  3. Struct.new(*keys).new(*values)
  4. end
  5. end
  6.  
  7.  
  8. # then use it like this
  9.  
  10. h = {:foo => 'bar', :baz => 'boz'}
  11.  
  12. s = h.to_struct("NameOfMyStruct")

Report this snippet  

You need to login to post a comment.