如何删除哈希中的空字符串

时间:2016-05-04 12:12:29

标签: ruby hash

{"name"=>"XYZ","address"=>{"street"=>{"street_address"=>"","city"=>"City name"}},"form"=>{"id"=>11,"f_name"=>""},"test"=""}

我想得到:

{"name"=>"XYZ","address"=>{"street"=>{"city"=>"City name"}},"form"=>{"id"=>11}}

如何删除空字符串?

3 个答案:

答案 0 :(得分:4)

hash = {"name"=>"XYZ",
        "address"=>{"street"=>{"street_address"=>"","city"=>"City name"}},
        "form"=>{"id"=>11,"f_name"=>""},
        "test"=>""}

def remove_blanks hash
  hash.map do |k, v|
    v == '' ? nil : [k, v.is_a?(Hash) ? remove_blanks(v) : v]
  end.compact.to_h
end

remove_blanks hash

#⇒ {
#  "address" => {
#    "street" => {
#      "city" => "City name"
#    }
#  },
#     "form" => {
#    "id" => 11
#  },
#     "name" => "XYZ"
# }

答案 1 :(得分:1)

我尝试了Proc

 > hash = {"name"=>"XYZ","address"=>{"street"=>{"street_address"=>"","city"=>"City name"}},"form"=>{"id"=>11,"f_name"=>""},"test"=>""}
 > remove_blank = Proc.new { |k, v| v.delete_if(&remove_blank) if v.is_a?(Hash); v == "" }
 > hash.delete_if &remove_blank
 #Output:

# {
#   "name"=>"XYZ", 
#   "address"=>
#     {
#       "street"=>
#         {
#           "city"=>"City name"
#         }
#     }, 
#   "form"=>
#     {
#       "id"=>11
#     }
# }

答案 2 :(得分:1)

require 'active_support/core_ext/object/blank'

def clean_hash(hash)
  hash.each do |key, value|
    if value.is_a?(Hash)
      clean_hash(value)
    else
      hash.delete(key) if value.blank?
    end
  end
end