Sha256: 98a0f92bdde511ac069574d093501f599e6b98a0340984a5359481a9e003cb22

Contents?: true

Size: 922 Bytes

Versions: 49

Compression:

Stored size: 922 Bytes

Contents

# frozen_string_literal: true

class Hash
  unless Hash.instance_methods(false).include?(:compact)
    # Returns a hash with non +nil+ values.
    #
    #   hash = { a: true, b: false, c: nil }
    #   hash.compact        # => { a: true, b: false }
    #   hash                # => { a: true, b: false, c: nil }
    #   { c: nil }.compact  # => {}
    #   { c: true }.compact # => { c: true }
    def compact
      select { |_, value| !value.nil? }
    end
  end

  unless Hash.instance_methods(false).include?(:compact!)
    # Replaces current hash with non +nil+ values.
    # Returns +nil+ if no changes were made, otherwise returns the hash.
    #
    #   hash = { a: true, b: false, c: nil }
    #   hash.compact!        # => { a: true, b: false }
    #   hash                 # => { a: true, b: false }
    #   { c: true }.compact! # => nil
    def compact!
      reject! { |_, value| value.nil? }
    end
  end
end

Version data entries

49 entries across 49 versions & 8 rubygems

Version Path
activesupport-5.2.8.1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.8 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.7.1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.7 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.6.3 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.6.2 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.6.1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.6 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.6 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.5 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.5 lib/active_support/core_ext/hash/compact.rb
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.1/lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.4 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.3 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.2 lib/active_support/core_ext/hash/compact.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.1 lib/active_support/core_ext/hash/compact.rb
zuora_connect_ui-0.10.0 vendor/ruby/2.6.0/gems/activesupport-5.2.3/lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4 lib/active_support/core_ext/hash/compact.rb
activesupport-5.2.4.rc1 lib/active_support/core_ext/hash/compact.rb