Posted By

pmd on 10/11/08


Tagged

hash struct


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

sergeizen
webstic


Nested hash to nested struct


 / Published in: Ruby
 

URL: http://www.roscripts.com/snippets/show/20

  1. # Nested hash to nested struct.
  2.  
  3. # From: http://www.roscripts.com/snippets/show/20
  4. # Author: Mike Hasting (duvion)
  5.  
  6. # Note: An empty string used as a key will cause 1.8 to choke
  7.  
  8. class Hash
  9. def to_struct(struct_name)
  10. Struct.new(struct_name,*keys).new(*values)
  11. end
  12. end
  13.  
  14. if $0 == __FILE__
  15. h = {"name"=>"Dan","age"=>33,"address"=>{"street"=>"Burlington rd, 33"}}
  16.  
  17. h["address"]=h["address"].to_struct("B")
  18. s = h.to_struct("Foo")
  19.  
  20. puts s.inspect
  21. puts "name: " + s.name
  22. puts "age: " + s.age.to_s
  23. puts "street: " + s.address.street
  24. end

Report this snippet  

You need to login to post a comment.