How to remove empty string in hash

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

Leave a Comment