Skip to content

Instantly share code, notes, and snippets.

@hynkle
Created August 8, 2011 20:33
Show Gist options
  • Save hynkle/1132666 to your computer and use it in GitHub Desktop.
Save hynkle/1132666 to your computer and use it in GitHub Desktop.
initialization of hash of arrays
h = Hash.new([])
h[:cats] << "Mittens"
h[:dogs] << "Fifi"
# At this point, I would like h to be
# {:cats => ["Mittens"}, :dogs => ["Fifi"]}
# Instead, it's just {}.
# Obviously this problem is easy to solve, but only at increased verbosity.
# It feels like it's something that should be able to be done in three lines.
# Best three-line approach I can come up with:
h = Hash.new{|h,k| h[k] = []}
h[:cats] << "Mittens"
h[:dogs] << "Fifi"
# But I really don't like that first line. I'd be okay with Hash.new{[]},
# but that doesn't mean the same thing as Hash.new{|h,k| h[k] = []}, because
# "It is the block's responsibility to store the value in the hash if required."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment