module Corefines::Hash::Only

@!method only(*keys)

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

@param *keys the keys to include in the hash.
@return [Hash] a new hash with only the specified key/value pairs.

@!method only!(*keys)

Removes all key/value pairs except the ones specified by _keys_.

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

@see #only
@param *keys (see #only)
@return [Hash] a hash containing the removed key/value pairs.

Public Instance Methods

only(*keys) click to toggle source
# File lib/corefines/hash.rb, line 133
def only(*keys)
  # Note: self.dup is used to preserve the default_proc.
  keys.each_with_object(dup.clear) do |k, hash|
    hash[k] = self[k] if has_key? k
  end
end
only!(*keys) click to toggle source
# File lib/corefines/hash.rb, line 140
def only!(*keys)
  deleted = keys.each_with_object(dup) do |k, hash|
    hash.delete(k)
  end
  replace only(*keys)

  deleted
end