我正在尝试将提供的Hash中的不同“Name”值连接成一个字符串。因此输出应该是一个包含所有“Name”值的数组或字符串。
我的困难在于,嵌套水平在两到四个父母之间变化。
我试图以两种方式解决它:
不幸的是,相关问题中给出的答案似乎都没有。我相信这很简单,但我似乎无法弄明白。非常感谢
my_hash = { "BreadCrumbs" => {
"Id" => 375,
"Name" => "Willingen",
"Parent" => {
"Id" => 52272,
"Name" => "Wintersport-Arena Sauerland",
"Parent" => {
"Id" => 8,
"Name" => "Germany"
}
}
}
}
答案 0 :(得分:2)
▶ hash = { "BreadCrumbs" => {
▷ "Id" => 375,
▷ "Name" => "Willingen",
▷ "Parent" => {
▷ "Id" => 52272,
▷ "Name" => "Wintersport-Arena Sauerland",
▷ "Parent" => {
▷ "Id" => 8,
▷ "Name" => "Germany"
▷ }
▷ }
▷ }}
▶ def concat hash
▷ [hash['Name'], hash['Parent'] ? concat(hash['Parent']) : nil]
▷ end
▶ (concat hash['BreadCrumbs']).flatten.compact
#⇒ ["Willingen", "Wintersport-Arena Sauerland", "Germany"]
我不会在每次迭代时展平,以便结果仍然包含层次结构:
▶ concat hash['BreadCrumbs']
#⇒ ["Willingen", ["Wintersport-Arena Sauerland", ["Germany", nil]]]
请求的字符串作为结果:
▶ (concat hash['BreadCrumbs']).flatten.compact.join ', '
#⇒ "Willingen, Wintersport-Arena Sauerland, Germany"
答案 1 :(得分:0)
对于任意数量的级别,不使用递归:
def pull_names(hash)
h = hash
names = []
loop do
names << h["Name"]
return names unless h.key?("Parent")
h = h["Parent"]
end
end
假设:
hash = { "BreadCrumbs" => {
"Name" => "Willingen",
"Parent" => {
"Id" => 52272,
"Name" => "Wintersport-Arena Sauerland",
"Parent" => {
"Id" => 8,
"Name" => "Germany",
"Parent" => {
"Id" => 1,
"Name" => "Bora Bora"
}
}
}
}
}
然后:
arr = pull_names hash["BreadCrumbs"]
#=> ["Willingen", "Wintersport-Arena Sauerland", "Germany", "Bora Bora"]
arr.join(' ')
#=> "Willingen Wintersport-Arena Sauerland Germany Bora Bora"