如何从子哈希

时间:2016-01-14 07:35:51

标签: ruby-on-rails ruby ruby-on-rails-4

h = { "name"=>"test", "address"=>"test address", "phone"=>"", 
      "users_attributes"=>{
        "0"=>{"id"=>"26", "email"=>"test@example.com",
              "password"=>"", "password_confirmation"=>""
        }
      }
    }

我想从此哈希

中删除"password"=>"", "password_confirmation"=>""

我试过了:

sanitize_params = Proc.new do |k, v|
  v.delete_if(&sanitize_params) if v.kind_of?(Hash)
  v.empty?
end
h.delete_if &sanitize_params

我不想删除第一级的值(即我不想删除"phone"=>""。)。但它删除了所有空白值。

怎么可能?

2 个答案:

答案 0 :(得分:3)

您可以使用递归进行任意数量的嵌套:

def purge_empties(h, top_level=true)
  h.each_with_object({}) do |(k,v),g|
    case v
    when Hash
      g[k] = purge_empties(v, false)
    else
      g[k] = v if top_level || !v.empty?
    end
  end
end

h = { "name"=>"test", "address"=>"test address", "phone"=>"", 
      "users_attributes"=>{
        "0"=>{"id"=>"26", "email"=>"test@example.com",
              "password"=>"", "password_confirmation"=>"",
              "one_more_level"=>{ "cat"=>"meow", "dog"=>"" }
        }
      }
    }

purge_empties(h)
  #=> { "name"=>"test", "address"=>"test address", "phone"=>"",
  #     "users_attributes"=>{
  #       "0"=>{
  #         "id"=>"26", "email"=>"test@example.com",
  #         "one_more_level"=>{"cat"=>"meow"}
  #       }
  #     }
  #   } 

答案 1 :(得分:0)

h['users_attributes']['0'].delete("password") &&
    h['users_attributes']['0'].delete("password_confirmation")
全球

或更多

h['users_attributes']['0'].delete_if {|key, value| value.empty? }