Module: Corefines::Hash::Except

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#except(*keys) ⇒ Hash

Returns a new hash without the specified key/value pairs.

Examples:

hash = { a: 1, b: 2, c: 3, d: 4 }
hash.except(:a, :d)  # => { b: 2, c: 3 }
hash  # => { a: 1, b: 2, c: 3, d: 4 }

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/corefines/hash.rb', line 56

module Except
  refine ::Hash do
    def except(*keys)
      keys.each_with_object(dup) do |k, hash|
        hash.delete(k)
      end
    end

    def except!(*keys)
      keys.each_with_object(dup.clear) do |k, deleted|
        deleted[k] = delete(k) if has_key? k
      end
    end
  end
end

#except!(*keys) ⇒ Hash

Removes the specified keys/value pairs in-place.

Examples:

hash = { a: 1, b: 2, c: 3, d: 4 }
hash.except(:a, :d)  # => { b: 2, c: 3 }
hash  # => { b: 2, c: 3 }

See Also:


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/corefines/hash.rb', line 56

module Except
  refine ::Hash do
    def except(*keys)
      keys.each_with_object(dup) do |k, hash|
        hash.delete(k)
      end
    end

    def except!(*keys)
      keys.each_with_object(dup.clear) do |k, deleted|
        deleted[k] = delete(k) if has_key? k
      end
    end
  end
end