I am trying to create a hash that has a key and an array of values associated with the key. So I was doing something like this
hash = Hash.new
and then later when I have a key I would do this
hash[key] << new_thing
but this fails if hash[key] is nil , so I added this statement before trying to append the new_thing to the array.
hash[key] = Array.new unless hash[key]
hash[key] << new_thing
I thought I could eliminate the added statement by changing the definition of hash to
hash = Hash.new Array.new
but this does not work because each entry shares the same array, what I really need is this
hash = Hash.new { |h,k| h[k] = Array.new }
I know I am probably splitting hairs but, I am just curious, what would be the "ruby" way to do this?
EDIT: Ultimately what I ended up doing is using group_by. I realize it was not obvious from my question that I was trying to use this structure to group objects with the same property together in a hash. I am including this to encourage others that may find themselves using a similar structure for a similar purpose to check out group_by
["A", 1, "b", 3].group_by { |i| i.class }
=> {String=>["A", "b"], Fixnum=>[1, 3]}