Created
February 22, 2013 17:32
-
-
Save rogercampos/5015169 to your computer and use it in GitHub Desktop.
The truth behind Hash default value
This file contains hidden or 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
# http://www.ruby-doc.org/core-1.9.3/Hash.html#method-c-new | |
# ... It is the block’s responsibility to store the value in the hash if required. | |
cuca = Hash.new([]) | |
cuca["ola"] << 12 # ~ [] << 12 | |
p cuca # => {} | |
cuca = Hash.new([]) | |
cuca["ola"] = cuca["ola"] << 12 | |
p cuca # => {"ola"=>[12]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When you use Hash.new() this means that will be returned instead of nil when accessing non-existing keys. But this WILL NOT associate the returned object as a value for the requested key. Simple enough, but leads to "i don't fucking know why this is'nt working" situations. It's one of those things that one expect ruby to do by itself.