Created
August 8, 2011 20:33
-
-
Save hynkle/1132666 to your computer and use it in GitHub Desktop.
initialization of hash of arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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