ruby adding to hash with array value

Viewed 26211

I tried the following ruby code, which I thought would return a hash of word lengths to the words with those lengths. Instead it is empty.

map = Hash.new(Array.new)    
strings = ["abc","def","four","five"]
strings.each do |word|
  map[word.length] << word  
end   

However, if I modify it to

map = Hash.new
strings = ["abc","def","four","five"]
strings.each do |word|
  map[word.length] ||= []
  map[word.length] << word  
end

It does work.

Doesn't the first version just create a hash whose default values are an empty array? In this case, I don't understand why the 2 blocks give different values.

3 Answers
Related