Nested hash to nested struct


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.