gpt4 book ai didi

arrays - 使用 ruby​​ 从数组创建嵌套哈希

转载 作者:行者123 更新时间:2023-12-04 16:04:38 24 4
gpt4 key购买 nike

我正在尝试将数组中的数据重新排列为散列格式,但我使用嵌套 if 时搞砸了

示例数据

[
["England", "London", "University College London ", "Faculty of Law"],
["England", "London", "University College London ", "Faculty of Engineering"],
["England", "London", "Imperial College London", "Faculty of Medicine"],
["England", "Manchester", "University of Manchester", "Faculty of Engineering"]
]

预期输出

{:name=>"England", 
:level=>1,
:children=>[{:name=>"London",
:level=>2,
:children=>[{:name=>"University College London ",
:level=>3,
:children=>[{:name=>"Faculty of Law",
:level=>4,
:children=>[]},
{:name=>"Faculty of Engineering",
:level=>4, :children=>[]}]},
{:name=>"Imperial College London",
:level=>3,
:children=>[{:name=>"Faculty of Engineering",
:level=>4,
:children=>[]}]
}]
}]
}

希望我能提供清楚的解释

附言。编辑以显示我尝试过的内容首先我制作哈希数组然后做这样的事情我还以为不会这么糊涂呢

result = []
arr.each do |b|
if result.any? {|r| r[:name] == b[:name]}
if result.first[:children].any? {|r| r[:name] == b[:children].first[:name]}
if result.first[:children].any?{|c| c[:children].any? {|r| r[:name] == b[:children].first[:children].first[:name] && c[:name] == b[:children].first[:name] }}
if result.first[:children].any? {|r| r[:children].any? {|c| c[:children].any?{|k| k[:name] == b[:children].first[:children].first[:children].first[:name] && (c[:name] == b[:children].first[:children].first)}}}

else
result.first[:children].any?{|c| c[:children].any? {|r| r[:name] == b[:children].first[:children].first[:name] ; r[:children] << b[:children].first[:children].first[:children].first}}

end #fourth
else
result.first[:children].any? {|r| r[:name] == b[:children].first[:name]; r[:children] << b[:children].first[:children].first}
end
else
result.any? {|r| r[:name] == b[:name] ; r[:children] << b[:children].first}
end
else result << b
end
end

最佳答案

你可以这样递归:

def map_objects(array, level = 1)
new_obj = []
array.group_by(&:shift).each do |key, val|
new_obj << {:name=>key, :level=>level, :children=>map_objects(val, level + 1)} if key
end
new_obj
end

对于你的数组,它将像这样返回:

# [
# {:name => "England", :level => 1, :children => [
# {:name => "London", :level => 2, :children => [
# {:name => "University College London ", :level => 3, :children => [
# {:name => "Faculty of Law", :level => 4, :children => []
# },
# {:name => "Faculty of Engineering", :level => 4, :children => []
# }]
# },
# {:name => "Imperial College London", :level => 3, :children => [
# {:name => "Faculty of Medicine", :level => 4, :children => []
# }]
# }]
# },
# {:name => "Manchester", :level => 2, :children => [
# {:name => "University of Manchester", :level => 3, :children => [
# {:name => "Faculty of Engineering", :level => 4, :children => []
# }]
# }]
# }]
# }
# ]

关于arrays - 使用 ruby​​ 从数组创建嵌套哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299696/

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