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]
p a.keys # => []
p a.values # => []
# Explicitly add an array for all nodes before creating
b = Hash.new
b[:key] ||= []
b[:key] << 2 # => [2]
p b # => {:key=>[2]}
p b.keys # => [:key]
Ruby version 1.8.7