2011-10-05 174 views
-2

我需要写脚本帮助我在保存之前清理散列哈希的帮助。哪个级别的标题是空的,需要删除。以下是示例散列。遍历和更新散列哈希的哈希

运行脚本

Questions= { 
     "0"=> 
       { 
        "title"=>"Question checkbox", 
        "id"=>"1", 
        "options_attributes"=> 
         { 
          "0"=>{"title"=>"1", "id"=>"1"}, 
          "1"=>{"title"=>"2", "id"=>"2"} 
         }, 
        "question_type_id"=>"4" 
       }, 
     "1"=> 
       { 
        "title"=>"Question Radio", 
        "id"=>"2", 
        "options_attributes"=> 
         { 
          "0"=> 
           { 
            "title"=>"yes", "id"=>"3" 
           }, 
          "1"=> 
           { 
            "title"=>"no", "id"=>"4" 
           }, 
          "2"=> 
           { 
            "title"=>"", "id"=>"" 
           } 
         }, 
        "question_type_id"=>"3" 
       }, 
     "2"=> 
       { 
        "title"=>"", 
        "options_attributes"=> 
         { 
          "0"=>{"title"=>"", "id"=>""}, 
          "1"=>{"title"=>"", "id"=>""} 
         }, 
        "question_type_id"=>"1" 
       } 
    } 

运行脚本所需的结果

Questions= { 
    "0"=> 
      { 
       "title"=>"Question checkbox", 
       "id"=>"1", 
       "options_attributes"=> 
        { 
         "0"=>{"title"=>"1", "id"=>"1"}, 
         "1"=>{"title"=>"2", "id"=>"2"} 
        }, 
       "question_type_id"=>"4" 
      }, 
    "1"=> 
      { 
       "title"=>"Question Radio", 
       "id"=>"2", 
       "options_attributes"=> 
        { 
         "0"=> 
          { 
           "title"=>"yes", "id"=>"3" 
          }, 
         "1"=> 
          { 
           "title"=>"no", "id"=>"4" 
          } 
        }, 
       "question_type_id"=>"3" 
      }, 
} 

回答

3

之后之前这里有修剪你的包含 “称号” 任何哈希树=> “” 的脚本。

def prune hash 
    if hash.class == Hash 
    hash.delete_if{|k,v| v["title"] == ""} 
    hash.each{|k,v| prune v} 
    else 
    hash 
    end 
end 

result = prune Questions