Module: Corefines::Hash::Only

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#only(*keys) ⇒ Hash

Returns a new hash with only the specified key/value pairs.

Examples:

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 }

Parameters:

  • *keys

    the keys to include in the hash.

Returns:

  • (Hash)

    a new hash with only the specified key/value pairs.


131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/corefines/hash.rb', line 131

module Only
  refine ::Hash do
    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

    def only!(*keys)
      deleted = keys.each_with_object(dup) do |k, hash|
        hash.delete(k)
      end
      replace only(*keys)

      deleted
    end
  end
end

#only!(*keys) ⇒ Hash

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

Examples:

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

Parameters:

  • *keys

    the keys to include in the hash.

Returns:

  • (Hash)

    a hash containing the removed key/value pairs.

See Also:


131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/corefines/hash.rb', line 131

module Only
  refine ::Hash do
    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

    def only!(*keys)
      deleted = keys.each_with_object(dup) do |k, hash|
        hash.delete(k)
      end
      replace only(*keys)

      deleted
    end
  end
end