Invalid hash default
I tried the following pieces of code today and I don't understand why different results occur between them. As far as I understand, they are the same.
One uses the default off Hash
and the other creates an empty array for the key before it's available.
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
a source to share
When you did a[:key] << 2
, you put that default empty array and added 2 to it (changing the actual array, not the reference), preventing the hash object from a
knowing that you changed something. You changed the a
default object, so you'll see this as well:
p a[:wat] #=> [2]
p a[:anything] #=> [2]
In the second example, you have created a new array and are using b[:key]=
that tells you b
that it has a value under this key.
Try this if you want the best of both worlds:
c = Hash.new([])
c[:key] += [2]
This will access c[:key]
and create a new array with +
and reassign it.
a source to share