Skip to content

Instantly share code, notes, and snippets.

@aleonjob
Last active March 12, 2017 12:52
Show Gist options
  • Save aleonjob/b7f34c603204eb201d888f9d74f36ed3 to your computer and use it in GitHub Desktop.
Save aleonjob/b7f34c603204eb201d888f9d74f36ed3 to your computer and use it in GitHub Desktop.
Override the Hash class to add a method to perform a deep strip for all levels of a hash object. This is useful when parsing json/xml responses.
class Hash
class << self
def strip_hash_values(hash)
hash.each { |_key, value| deep_strip!(value) }
end
def strip_array_values(array)
array.each { |value| deep_strip!(value) }
end
def deep_strip!(value)
case value
when Hash then strip_hash_values(value)
when Array then strip_array_values(value)
when String then value.strip!
else value
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment