Created
September 3, 2012 13:06
-
-
Save marcocarvalho/3609215 to your computer and use it in GitHub Desktop.
Hash with Initial 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
# Ao invés de fazer: | |
# dentro de uma iteração | |
h = {} | |
h[:somekey] = {} if h[:somekey].nil? | |
h[:somekey][:otherkey] = [] if h[:somekey][:otherkey].nil? | |
h[:somekey][:otherkey] << item_da_teracao | |
# Teremos um hash: { somekey: { :otherkey => [1, 2, 3, 4] } } | |
# Para economizar linhas e lógica poderíamos | |
h = Hash.new( Hash.new( [] ) ) | |
h[:somekey][:otherkey] << 1 | |
h[:somekey][:otherkey] << 2 | |
h[:somekey][:otherkey] << 3 | |
h[:somekey][:otherkey] << 4 | |
# só que com esse aprouch temos um hash "vazio" | |
h.size # 0 | |
h.keys # [] | |
# Contudo se acessarmos as keys setadas ele retorna o array certo. | |
h[:somekey][:otherkey] # [1, 2, 3, 4] | |
# Bug? Ou braço curtisse minha? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hash.new { |hash, key| hash[key] = Hash.new &hash.default_proc }
Resolve :D