[ {"Jeans"=>[ -6ren">
gpt4 book ai didi

ruby - 解析嵌套 Ruby 数组/YAML 的最快方法

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

从这个结构中提取 third level 元素的最干净的方法是什么,前提是它不是对称的:

   yaml = [
{"Collection"=>[
{"Jeans"=>[
{"Trends"=>[
{"Building on basics"=>"Jeans"},
{"Unexpected pairings"=>"Jeans"},
{"Retro chic"=>"Jeans"} # extract me
]},
{"Styles"=>[
{"Straight Leg"=>"Straight Leg"},
{"Bootcut"=>"Bootcut"},
{"Trouser"=>"Trouser"},
{"Slim Leg"=>"Slim Leg"}
]},
{"Wash"=>[
{"Blues"=>"Blues"},
{"Black/Grey"=>"BlackGrey"},
{"Whites"=>"Summer Whites"},
{"Colors"=>"Colors"},
{"Resin"=>"Resin"}
]},
{"Details"=>[
{"Embroidered"=>"Embroidered"},
{"Tuxedo"=>"Tuxedo"},
{"Jeweled"=>"Jeweled"}
]}
]},
{"Bodyshapers"=>[
{"All"=>[
{"All"=>"BodyShapers"}
]}
]}
]},
{"Lift Tuck"=>nil},
{"Find Us" =>[
"By City",
"International Websites",
"Online Retailers"
]},
{"Your Stories"=>nil},
{"The Skinny"=>[
"Trends",
"Behind the Scenes",
"VIP Events",
"In the News",
"Win a Pair"
]}
]

最佳答案

我不知道最简单的方法,但像这样的方法会起作用:

class NthElements
include Enumerable

def initialize(yaml, n = 3)
@yaml = yaml
@n = n
end

def each(&block)
traverse(@yaml, 0, &block)
end

private
def traverse(value, level, &block)
if level == @n + 1
block.call(value)
return
end

case value
when Array
value.each { |next_value| traverse(next_value, level + 1, &block) }
when Hash
value.values.each { |next_value| traverse(next_value, level, &block) }
end
end
end

NthElements.new(yaml).each{|val| p val }

关于ruby - 解析嵌套 Ruby 数组/YAML 的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4741472/

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