Ruby将数组映射到哈希

时间:2017-06-30 19:23:00

标签: arrays ruby hash

我有一个2D数组,每行都有:

['John', 'M', '34']

我希望将每个哈希映射到Hash数组中,如:

{:Name=>"John", :Gender=>"M", :Age=>"34"}

有没有一种优雅的方式呢?

5 个答案:

答案 0 :(得分:6)

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"}]

答案 1 :(得分:4)

您可以尝试使用zip然后使用to_h(代表哈希)

例如:

[:Name, :Gender, :Age].zip(['John', 'M', '34']).to_h
=> {:Name=>"John", :Gender=>"M", :Age=>"34"}

Read more about zip here

And read about to_h here

答案 2 :(得分:3)

people = [['John', 'M', '34']]
keys = %i{Name Gender Age}

hashes = people.map { |person| keys.zip(person).to_h }
# => [{:Name=>"John", :Gender=>"M", :Age=>"34"}]

基本上我将两个数组组合成一个哈希(一个带键,一个带值)的方法是使用Array#zip。这可以将[1,2,3][4,5,6]转换为[[1,4], [2,5], [3,6]]

此结构可以通过to_h

轻松转换为哈希

答案 3 :(得分:1)

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

答案 4 :(得分:0)

这是另外一种方法

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"}]