[英]Ruby mapping array into hash
I have a 2D array with each row like: 我有一个2D数组,每行如:
['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) 您可以尝试使用
zip
然后to_h
(代表哈希)
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 . 基本上我将两个数组组合成一个哈希(一个带键,一个带值)的方法是使用Array#zip 。 This can turn
[1,2,3]
and [4,5,6]
into [[1,4], [2,5], [3,6]]
这可以将
[1,2,3]
和[4,5,6]
变成[[1,4], [2,5], [3,6]]
This structure can be easily turned into a hash via to_h
通过
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"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.