Ruby to hash mapping array
5 answers
array_of_rows.map { |n,g,a| { Name: n, Gender: g, Age: a } }
or
array_of_rows.map { |row| %i{Name Gender Age}.zip(row).to_h }
They give the same result, so choose one that you find clearer. For example, given this input:
array_of_rows = [
['John', 'M', '34'],
['Mark', 'M', '49']
]
any expression will give this output:
[{:Name=>"John", :Gender=>"M", :Age=>"34"},
{:Name=>"Mark", :Gender=>"M", :Age=>"49"}]
+6
source to share
people = [['John', 'M', '34']]
keys = %i{Name Gender Age}
hashes = people.map { |person| keys.zip(person).to_h }
# => [{:Name=>"John", :Gender=>"M", :Age=>"34"}]
Basically the way I turn on concatenating two arrays into a hash (one with keys, one with values) is to use Array # zip . It can turn [1,2,3]
and [4,5,6]
in[[1,4], [2,5], [3,6]]
This structure can easily be turned into a hash via to_h
+3
source to share
array_of_rows = [
['John', 'M', '34'],
['Mark', 'M', '49']
]
keys = ['Name', 'Gender', 'Age']
[keys].product(array_of_rows).map { |k,v| k.zip(v).to_h }
#=> [{"Name"=>"John", "Gender"=>"M", "Age"=>"34"},
# {"Name"=>"Mark", "Gender"=>"M", "Age"=>"49"}]
or
keys_cycle = keys.cycle
array_of_rows.map do |values|
values.each_with_object({}) { |value, h| h[keys_cycle.next]=value }
do
+1
source to share