2012-02-02 39 views
1

我有一個使用JSON.parse得到的散列。我在那個時候插入到db中。數據結構使用作爲樹,所以我可以有一個這樣的哈希:在紅寶石中遞歸搜索散列並返回項目數組

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的數組。我看到這個問題Traversing a Hash Recursively in Ruby,但它似乎不同。有沒有辦法遞歸搜索散列並返回所有這些元素?理想情況下,空items_attributes應該返回沒有任何東西,而不是零。

THX

回答

2

你可以做這樣的事情:

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"} 
3

試試這個:

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 

現在讓我們來測試該函數:

>> 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"]