0

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?

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting use of Array#product here.
both you and @tadman have very enlightening answers, thank you :)
2

As is often the case the answer lies in the power of Enumerable:

Hash[
  department.map do |d|
    [
      d,
      Hash[
        month.map do |m|
          [ m, '' ]
        end
      ]
    ]
  end
]

There's a lot going on in here, but it boils down to a two part process, one converting the department list into a hash of hashes, and a second part to populate that with a converted month structure.

Hash[] is a handy way of converting key/value pairs into a proper Hash structure.

Comments

0
department = ['name1', 'name2', 'name3']
month = ['jan', 'feb', 'mar', 'etc']

month_hash = month.each_with_object({}) { |m, res| res[m] = '' }
result = department.each_with_object({}) { |name, res| res[name] = month_hash.dup }

p result

This way you could build month_hash, and then use it to build result hash, that you need

Comments

0

Here's how I would do it.

1) Make a Hash out of your months array

month_hash = Hash[month.map { |m| [m ,''] }]

2) Make a Hash out of your department array, inserting the newly made month hash.

result_hash = Hash[department.map { |d| [d, month_hash] }]

Comments

0
month = ['jan', 'feb', 'mar', 'etc']
department = ['name1', 'name2', 'name3']

month_hash = month.map {|m| [m, '']}.to_h
p department.map {|d| [d, month_hash]}.to_h

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.