Skip to content

Instantly share code, notes, and snippets.

@rogercampos
Created February 22, 2013 17:32
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 rogercampos/5015169 to your computer and use it in GitHub Desktop.
Save rogercampos/5015169 to your computer and use it in GitHub Desktop.
The truth behind Hash default value
# 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]}
@rogercampos
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment