gpt4 book ai didi

arrays - Ruby 数组数组转换为哈希数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:07 24 4
gpt4 key购买 nike

我有一个数组:

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

最佳答案

你可以这样做:

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

请记住,这仅在元素与字段的顺序相同时才有效。

关于arrays - Ruby 数组数组转换为哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com