Module: Corefines::Hash::Compact

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#compactHash

Returns a new hash with no key-value pairs which value is nil.

Examples:

hash = { a: true, b: false, c: nil }
hash.compact # => { a: true, b: false }
hash # => { a: true, b: false, c: nil }
{ c: nil }.compact # => {}

Returns:

  • (Hash)

    a new hash with no key-value pairs which value is nil.


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/corefines/hash.rb', line 22

module Compact
  refine ::Hash do
    def compact
      reject { |_, value| value.nil? }
    end

    def compact!
      delete_if { |_, value| value.nil? }
    end
  end
end

#compact!Hash

Removes all key-value pairs from the hash which value is nil. Same as #compact, but modifies self.

Returns:


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/corefines/hash.rb', line 22

module Compact
  refine ::Hash do
    def compact
      reject { |_, value| value.nil? }
    end

    def compact!
      delete_if { |_, value| value.nil? }
    end
  end
end