Last active
August 29, 2015 14:05
-
-
Save lmarburger/8a833e3224c957a1d14a to your computer and use it in GitHub Desktop.
Ruby's hash default value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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