Skip to content

Instantly share code, notes, and snippets.

@lmarburger
Last active August 29, 2015 14:05
Show Gist options
  • Save lmarburger/8a833e3224c957a1d14a to your computer and use it in GitHub Desktop.
Save lmarburger/8a833e3224c957a1d14a to your computer and use it in GitHub Desktop.
Ruby's hash default value
$x = 0
h = Hash.new {|h, k| h[k] = $x += 1 }
p h[:a]
p h[:a]
p h[:b]
p h
$y = 0
i = Hash.new { $y += 1 }
p i[:a]
p i[:b]
p i[:a]
p i
j = Hash.new(0)
p j[:a]
p j
broken = Hash.new { [] }
broken[:one] << 1
broken[:two] << 2
p broken #=> {}
works = Hash.new {|h, k| h[k] = [] }
works[:one] << 1
works[:two] << 2
p works #=> {:one=>[1], :two=>[2]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment