Initialize a hash with all 0 values based on two arrays Given two arrays (for instance a list of people and a list of subjects), I need to initialise a Hash with all zeros for all possible combinations of these two arrays. I can manage to do that with the code on the bottom, but it seems like there should be a less convoluted, more elegant way to do this.

people = %w(tom mary rob)
subjects = %w(math english)

Hash[people.map { |person| [person, Hash[subjects.map { |subject| [subject, 0] }]]}]

# output: =&gt; {"tom"=&gt;{"math"=&gt;0, "english"=&gt;0},
# "mary"=&gt;{"math"=&gt;0, "english"=&gt;0},
# "rob"=&gt;{"math"=&gt;0, "english"=&gt;0}}
Conceptually, that's the way to go. I'd just propose some small changes:


Use Array#to_h instead of Hash#[] 
This line is too long, split it in multiple lines.


So I'd write:

scores = people.map do |person|
  person_scores = subjects.map { |subject| [subject, 0] }.to_h 
  [person, person_scores]
end.to_h