我有一个二维数组,每行看起来像:
['John', 'M', '34']
我想把它映射到一个哈希数组中,每个哈希看起来像:
{:Name=>"John", :Gender=>"M", :Age=>"34"}
有没有一种优雅的方法来做到这一点?
array_of_rows.map { |n,g,a| { Name: n, Gender: g, Age: a } }
或者
array_of_rows.map { |row| %i{Name Gender Age}.zip(row).to_h }
array_of_rows = [
['John', 'M', '34'],
['Mark', 'M', '49']
]
[{:Name=>"John", :Gender=>"M", :Age=>"34"},
{:Name=>"Mark", :Gender=>"M", :Age=>"49"}]
zip
,然后使用to_h
(表示转换为哈希)。[: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"}]
[1,2,3]
和 [4,5,6]
转换为 [[1,4], [2,5], [3,6]]
。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"}]
或者
keys_cycle = keys.cycle
array_of_rows.map do |values|
values.each_with_object({}) { |value, h| h[keys_cycle.next]=value }
do
这里还有一种方法可以实现
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"}]
%i{Name Gender Age}
硬编码。 - Cary Swoveland