I am trying to create a hash with values as arrays. I am adding elements to those arrays, but for some reason, the hash becomes empty after it runs. I’m not sure why at all. Here is my code
def function(words)
hash = Hash.new([]) # default value of empty list
words.each do |word|
sorted = word.chars.sort.join # sort the string
hash[sorted] << word
## hash becomes empty here
end
return hash
end
puts function ['cars', 'for', 'potatoes', 'racs', 'four']
I’m new to Ruby and I have no idea why the hash is emptying it self. I’ve written a similar algorithm with the same logic in Python and it works absolutely fine. Any suggestions?
The problem is the default hash value you give is a mutable value (partially, at least—see below), you need to instead use
Hash.new’s block parameter:You get the correct result:
The problem with what you have is that
hash[sorted]returns[], but never actually assigns to it. So you change the array, but never put it in the hash. If you use+=instead (leaving yourHash.new([]), you can that this also works: