Skip to content

Instantly share code, notes, and snippets.

@probablykabari
Created September 3, 2014 17:52
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 probablykabari/d39146a0bb556d411442 to your computer and use it in GitHub Desktop.
Save probablykabari/d39146a0bb556d411442 to your computer and use it in GitHub Desktop.
Quick look at hash nesting
hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
hash["down"]["in-the"]["basement"] = "hello?"
hash
# => {"down"=>{"in-the"=>{"basement"=>"hello?"}}}
hash.has_key?("i-do-not")
# => false
hash.default = lambda{|h,k| h[k] = "bankai!" } # no longer a deeply nested/fun hash
hash["not"]["nested"] = ":("
# NoMethodError: undefined method `[]=' for #<Proc:0x00000101b44888@(irb):69 (lambda)>
hash["dang"] = "I get it"
hash
# => {"down"=>{"in-the"=>{"basement"=>"hello?"}}, "dang"=>"I get it"}
@robertzk
Copy link

robertzk commented Sep 3, 2014

Maybe add Hash#nested to lib that makes a blank new hash with this functionality?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment