Skip to content

Instantly share code, notes, and snippets.

@nocnoi
nocnoi / Initialize hashes
Last active Nov 23, 2017
Initializing hashes and subhashes
View Initialize hashes
# 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
You can’t perform that action at this time.