Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created October 19, 2012 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterhellberg/3918727 to your computer and use it in GitHub Desktop.
Save peterhellberg/3918727 to your computer and use it in GitHub Desktop.
Hash Autovivification and eval trickery
data = {
"section1.stuff"=>"as",
"section1.stuff2" => "qw",
"section2.stuff3" => "zx"
}
hash = Hash.new(&(p=lambda{|h,k|h[k]=Hash.new(&p)}))
data.each_with_object(hash) { |(k,v), h|
eval "h['#{k.gsub('.',"']['")}']='#{v}'"
}
hash.inspect # => "{\"section1\"=>{\"stuff\"=>\"as\", \"stuff2\"=>\"qw\"}, \"section2\"=>{\"stuff3\"=>\"zx\"}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment