遍历并更新哈希红宝石的散列

时间:2011-10-05 07:49:19

标签: ruby-on-rails ruby

我需要帮助来编写脚本,帮助我在保存之前清除哈希值。哪个级别标题为空,需要删除。下面是示例哈希。

在运行脚本之前

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

1 个答案:

答案 0 :(得分:3)

这是一个脚本,用于修剪包含“title”=>的任何哈希值的树。 “”。

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