Sha256: 03124574a0cb5ffeeb8ad466096fe2aec64abf712bc0aa2be10b8c654a2d13d9

Contents?: true

Size: 891 Bytes

Versions: 23

Compression:

Stored size: 891 Bytes

Contents

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

23 entries across 23 versions & 3 rubygems

Version Path
activesupport-5.1.7 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.7.rc1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.6.2 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.6.1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.6 lib/active_support/core_ext/hash/compact.rb
tdiary-5.0.8 vendor/bundle/gems/activesupport-5.1.5/lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.5 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.5.rc1 lib/active_support/core_ext/hash/compact.rb
pract6-0.1.0 .gem/ruby/2.3.0/gems/activesupport-5.1.4/lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.4 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.4.rc1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.3 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.3.rc3 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.3.rc2 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.3.rc1 lib/active_support/core_ext/hash/compact.rb
tdiary-5.0.5 vendor/bundle/gems/activesupport-5.1.2/lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.2 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.2.rc1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.1 lib/active_support/core_ext/hash/compact.rb
activesupport-5.1.0 lib/active_support/core_ext/hash/compact.rb