在ruby中递归搜索hash并返回一个项目数组

我有一个哈希,我从使用JSON.parse。 那时我正在插入db。 数据结构使用act作为树,所以我可以有这样的哈希:

category_attributes name: "Gardening" items_attributes: item 1: "backhoe" item 2: "whellbarrel" children_attributes name: "seeds" items_attributes item 3: "various flower seeds" item 4: "various tree seeds" children_attributes name: "agricultural seeds" items_attributes item 5: "corn" item 6: "wheat" 

对于这个哈希,我想返回所有items_attributes的数组。 我已经看到这个问题在Ruby中递归遍历Hash但它看起来有所不同。 有没有办法递归搜索哈希并返回所有这些元素? 理想情况下,空的items_attributes应该只返回nil而不是nil。

谢谢

你可以这样做:

 def collect_item_attributes h result = {} h.each do |k, v| if k == 'items_attributes' h[k].each {|k, v| result[k] = v } # <= tweak here elsif v.is_a? Hash collect_item_attributes(h[k]).each do |k, v| result[k] = v end end end result end puts collect_item_attributes(h) # => {"item 1"=>"backhoe", # "item 2"=>"whellbarrel", # "item 3"=>"various flower seeds", # "item 4"=>"various tree seeds", # "item 5"=>"corn", # "item 6"=>"wheat"} 

试试这个:

 def extract_list(hash, collect = false) hash.map do |k, v| v.is_a?(Hash) ? extract_list(v, (k == "items_attributes")) : (collect ? v : nil) end.compact.flatten end 

现在让我们测试一下这个function:

 >> input = { 'category_attributes' => { 'name' => "Gardening", 'items_attributes' => { 'item 1' => "backhoe", 'item 2' => "whellbarrel", 'children_attributes' => { 'name' => "seeds", 'items_attributes' => { 'item 3' => "various flower seeds", 'item 4' => "various tree seeds" }, 'children_attributes' => { 'name' => "agricultural seeds", 'items_attributes' => { 'item 5' => "corn", 'item 6' => "wheat" } } } } } } >> extract_list(input) => ["various flower seeds", "various tree seeds", "wheat", "corn", "backhoe", "whellbarrel"]