I have a 2D array with each row like:
['John', 'M', '34']
I want to map into an array of Hash with each hash like:
{:Name=>"John", :Gender=>"M", :Age=>"34"}
Is there an elegant way of doing that?
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 produce the same result, so pick the one you find clearer. For example, given this input:
array_of_rows = [
['John', 'M', '34'],
['Mark', 'M', '49']
]
either expression will yield this output:
[{:Name=>"John", :Gender=>"M", :Age=>"34"},
{:Name=>"Mark", :Gender=>"M", :Age=>"49"}]
You could try using zip
and then to_h
(which stands for to hash)
For example:
[:Name, :Gender, :Age].zip(['John', 'M', '34']).to_h
=> {:Name=>"John", :Gender=>"M", :Age=>"34"}
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 combine two arrays into a hash (one with keys, one with values) is to use Array#zip . This can turn [1,2,3]
and [4,5,6]
into [[1,4], [2,5], [3,6]]
This structure can be easily turned into a hash via to_h
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
Here is one more way to do this
array_of_rows = [
['John', 'M', '34'],
['Mark', 'M', '49']
]
keys = [:Name, :Gender, :Age]
array_of_rows.collect { |a| Hash[ [keys, a].transpose] }
#=>[{:Name=>"John", :Gender=>"M", :Age=>"34"}, {:Name=>"Mark", :Gender=>"M", :Age=>"49"}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.