patternrubyMinor
Initialize a hash with all 0 values based on two arrays
Viewed 0 times
arraysallwithhashtwobasedvaluesinitialize
Problem
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: => {"tom"=>{"math"=>0, "english"=>0},
# "mary"=>{"math"=>0, "english"=>0},
# "rob"=>{"math"=>0, "english"=>0}}Solution
Conceptually, that's the way to go. I'd just propose some small changes:
So I'd write:
- 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_hCode Snippets
scores = people.map do |person|
person_scores = subjects.map { |subject| [subject, 0] }.to_h
[person, person_scores]
end.to_hContext
StackExchange Code Review Q#105703, answer score: 5
Revisions (0)
No revisions yet.