Skip to content

Instantly share code, notes, and snippets.

@nocnoi
Last active November 23, 2017 08:54
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 nocnoi/55cbdd050df14d9fd27db55b4c748a31 to your computer and use it in GitHub Desktop.
Save nocnoi/55cbdd050df14d9fd27db55b4c748a31 to your computer and use it in GitHub Desktop.
Initializing hashes and subhashes
# Initialize missing values for subhashes
h = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) } #=> {}
h['a']['b']['c'] = 'd'
h #=> {"a"=>{"b"=>{"c"=>"d"}}}
# Initialize values for hash, for specific given keys
list = %w[ a b c ]
hash = Hash[list.collect { |i| [ i, 0 ] }]
# Initialize hash with default value of 0 for any given key
hash = Hash.new { |h, k| h[k] = 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment