Hash default value not being used
Posted
by ba
on Stack Overflow
See other posts from Stack Overflow
or by ba
Published on 2010-04-22T15:25:47Z
Indexed on
2010/04/22
16:03 UTC
Read the original article
Hit count: 203
Today I tried the following snippets of code and I don't understand why I get different results between them. As far as I can understand they are the same.
One uses the default value off Hash
and the other snippet creates an empty array for the key before it'll be accessed.
Anyone who understands what's going on? :)
# Hash default if the key doesn't have a value set is an empty Array
a = Hash.new([])
a[:key] << 2 # => [2]
p a # => {} nil
p a[:key] # => [2]
# Explicitly add an array for all nodes before creating
b = Hash.new
b[:key] ||= []
b[:key] << 2 # => [2]
p b # => {:key=>[2]}
© Stack Overflow or respective owner