alilland alilland - 6 months ago 8
Ruby Question

dynamically add keys and values to hash and hash within hash

I have an array of names

department = ['name1', 'name2', 'name3']


and an array of months

month = ['jan', 'feb', 'mar', 'etc']


I need to dynamically merge these arrays into hashes to look like this:

h = {'name1' => {'jan' => '', 'feb' => '', 'mar' => '', 'etc' => ''},
'name2' => {'jan' => '', 'feb' => '', 'mar' => '', 'etc' => ''}, 'name3' => {'jan' => '', 'feb' => '', 'mar' => '', 'etc' => ''}}


How would I go about dynamically adding keys into my hash?

Answer

Here is a way:

department
  .each_with_object({}) do |name, h|
     # taking an empty hash which will be holding your final output.
     h[name] = month.product([""]).to_h
   end

Read Array#product to know how month.product([""]) line is working. You can convert an array of array to hash using to_h.

Comments