Skip to content
Browse files

make Hash#extract! more symmetric with Hash#slice

  • Loading branch information...
1 parent 800604e commit 5d27338ab08496b41ef71c789e5ae4de0b3b8df7 @Mik-die Mik-die committed Jul 9, 2012
View
11 activesupport/CHANGELOG.md
@@ -1,5 +1,16 @@
## Rails 4.0.0 (unreleased) ##
+* Hash#extract! returns only those keys that present in the reciever.
+
+ {:a => 1, :b => 2}.extract!(:a, :x) # => {:a => 1}
+
+ *Mikhail Dieterle*
+
+* Hash#extract! returns the same subclass, that the reciever is. I.e.
+ HashWithIndifferentAccess#extract! returns HashWithIndifferentAccess instance.
+
+ *Mikhail Dieterle*
+
* Optimize ActiveSupport::Cache::Entry to reduce memory and processing overhead. *Brian Durand*
* Tests tag the Rails log with the current test class and test case:
View
6 activesupport/lib/active_support/core_ext/hash/slice.rb
@@ -32,9 +32,9 @@ def slice!(*keys)
# 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, 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({}) { |key, result| result[key] = delete(key) }
+ keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
end
end
View
17 activesupport/test/core_ext/hash_ext_test.rb
@@ -725,6 +725,23 @@ def test_extract
original = {:a => 1, :b => 2, :c => 3, :d => 4}
expected = {:a => 1, :b => 2}
+ assert_equal expected, original.extract!(:a, :b, :x)
+ end
+
+ def test_extract_nils
+ original = {:a => nil, :b => nil}
+ expected = {:a => nil}
+ extracted = original.extract!(:a, :x)
+
+ assert_equal expected, extracted
+ assert_equal nil, extracted[:a]
+ assert_equal nil, extracted[:x]
+ end
+
+ def test_indifferent_extract
+ original = {:a => 1, :b => 2, :c => 3, :d => 4}.with_indifferent_access
+ expected = {:a => 1, :b => 2}.with_indifferent_access
+
assert_equal expected, original.extract!(:a, :b)
end

0 comments on commit 5d27338

Please sign in to comment.
Something went wrong with that request. Please try again.