aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/hash/slice.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/hash/slice.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/hash/slice.rb26
1 files changed, 26 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb
new file mode 100644
index 0000000000..3d0f8a1e62
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/slice.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+class Hash
+ # Replaces the hash with only the given keys.
+ # Returns a hash containing the removed key/value pairs.
+ #
+ # hash = { a: 1, b: 2, c: 3, d: 4 }
+ # hash.slice!(:a, :b) # => {:c=>3, :d=>4}
+ # hash # => {:a=>1, :b=>2}
+ def slice!(*keys)
+ omit = slice(*self.keys - keys)
+ hash = slice(*keys)
+ hash.default = default
+ hash.default_proc = default_proc if default_proc
+ replace(hash)
+ omit
+ end
+
+ # Removes and returns the key/value pairs matching the given keys.
+ #
+ # { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
+ # { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
+ def extract!(*keys)
+ keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
+ end
+end