Ruby数组的数组为哈希数组

时间:2017-10-26 01:06:03

标签: arrays ruby hash

我有一个数组数组:

data = [
 ["Smith", "Bob", "Male"], 
 ["Jim", "Tim", "Male"],   
 ["Welch", "Anne", "Female"]
]

我如何将其转换为:

data = [
 {:first_name => "Smith", :last_name => "Bob", :gender => "Male"},  
 {:first_name => "Jim", :last_name => "Tim", :gender => "Male"}, 
 {:first_name => "Welch", :last_name => "Anne", :gender => "Female"}
]

3 个答案:

答案 0 :(得分:6)

您可以这样做:

fields = [:first_name, :last_name, :gender]
data.map {|row| fields.zip(row).to_h }

#=> [{:first_name=>"Smith", :last_name=>"Bob", :gender=>"Male"}, {:first_name=>"Jim", :last_name=>"Tim", :gender=>"Male"}, {:first_name=>"Welch", :last_name=>"Anne", :gender=>"Female"}] 

请注意,只有元素与字段的顺序相同时才会有效。

答案 1 :(得分:1)

您也可以使用Struct

presenter = Struct.new(:first_name, :last_name, :gender)
data.map { |e| presenter.new(*e).to_h }
#=> [{:first_name=>"Smith", :last_name=>"Bob", :gender=>"Male"}, 
#    {:first_name=>"Jim", :last_name=>"Tim", :gender=>"Male"}, 
#    {:first_name=>"Welch", :last_name=>"Anne", :gender=>"Female"}]

答案 2 :(得分:0)

fields = [:first_name, :last_name, :gender]
data.map{|d| Hash[fields.zip(d)]}