Search code examples
rubyhashmapblock

Hash.new{[]} - anything wrong with it?


Looking at @mu is too short's answer to another question, I tried a variation:

def anagrams(list)
  h = Hash.new{ [] }
  list.each_with_object(h){ |el, h| h[el.downcase.chars.sort] <<= el }
end

anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'])

(Blindly assuming there would be a<<= operator.) It works, but Hash.new{[]} is not idiomatic at all - I have not found any examples. Is there something wrong with it?


Solution

  • It's weird, because it doesn't make any use of what the block ctor provides, but the purpose of the block ctor is to return the default value--if you choose not to do anything with the |h, k|, that's your call.