gpt4 book ai didi

arrays - 在 ruby​​ 中将数组转换为散列

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

假设我有一个看起来像这样的数组

testarr = [["Actor", "Morgan", "33", ["A","B"]],
["Movie", "Titanic", "44", ["A","A"]],
["Actor", "Jack Black", "333", ["A","A"]]]

我想将其转换为哈希,最终将转换为 json。

我希望它看起来像

{

"Actor" => {
{ "name" : "Morgan",
"Age" : 33",
"Films: { "A", "B" }} ,

{ "name" : "Jack Black",
"Age" : 44",
"Films: { "A", "A" }}
}
"Movie" => {
{ "Title" : "Titanic"
"Gross" : "44"
"Actors" : { "A", "A" }
}
}

不确定确切的格式,但只要有意义即可。

我试过了

def hashing(arr)
hash = Hash.new

arr.each do |item|

if item[0] == "Movie"
item.delete("Movie")
hash["Movie"] = item
item["Title"] = item[1]
item["Movie"]["Box Office"] = item[2]
item["Movie"]["Actors"] = item[3]

else

item.delete("Actor")
hash["Actor"] = item

item["Actor"]["Name"] == item[1]
item["Actor"]["Age"] == item[2]
item["Actor"]["Filmography"] == item[3]

end

end

return hash

end

testarr = [["Actor", "Morgan", "33", ["dsfds","dsfdsf"]],
["Movie", "Titanic", "44", ["dsfds","dfdsf"]],
["Actor", "Jack Black", "333", ["ssdsfds","dsfdsf"]]]

puts hashing(testarr)

但是当我将数组项放入“Movie”和“Actor”然后尝试创建“Name”和“Age”之类的键时,它给了我一个错误。

我怎样才能按照自己的意愿制作这个?

最佳答案

testarr = [["Actor", "Morgan", "33", ["A","B"]],
["Movie", "Titanic", "44", ["A","A"]],
["Actor", "Jack Black", "333", ["A","A"]]]

a = Hash.new{ |h,k| h[k] = [] }

testarr.each do |arr|
b = {name: arr[1], age: arr[2], films: arr[3]}
a[arr[0]] << b
end

这会产生

{"Actor"=>[{"name"=>"Morgan", "age"=>"33", "films"=>["A", "B"]}, {"name"=>"Jack Black", "age"=>"333", "films"=>["A", "A"]}], "Movie"=>[{"name"=>"Titanic", "age"=>"44", "films"=>["A", "A"]}]}

关于arrays - 在 ruby​​ 中将数组转换为散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46643968/

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