Skip to content

Instantly share code, notes, and snippets.

@longlostnick
Created September 29, 2011 17:24
Show Gist options
  • Save longlostnick/1251339 to your computer and use it in GitHub Desktop.
Save longlostnick/1251339 to your computer and use it in GitHub Desktop.
Delete all empty/false elements from hash recursively
# (v.respond_to?(:empty?) ? v.empty? : !v) is basically rails' .blank? in plain ruby
class Hash
def delete_blank
delete_if do |k, v|
(v.respond_to?(:empty?) ? v.empty? : !v) or v.instance_of?(Hash) && v.delete_blank.empty?
end
end
end
@srghma
Copy link

srghma commented May 22, 2018

implementation that works for both hashes and arrays

module Helpers
  module RecursiveCompact
    extend self

    def recursive_compact(hash_or_array)
      p = proc do |*args|
        v = args.last
        v.delete_if(&p) if v.respond_to? :delete_if
        v.nil? || v.respond_to?(:"empty?") && v.empty?
      end

      hash_or_array.delete_if(&p)
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment