`Hash#extract!`: Clarify its docs and assert remaining value in `test_extract_nils`

This change emphasizes a remaining value after applying `extract!` on
a hash.
This commit is contained in:
bogdanvlviv 2020-09-26 20:16:22 +03:00
parent f40c17dcfa
commit ac18d0bbda
No known key found for this signature in database
GPG Key ID: E4ACD76A6DB6DFDD
2 changed files with 5 additions and 2 deletions

View File

@ -18,8 +18,9 @@ class Hash
# 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}
# hash = { a: 1, b: 2, c: 3, d: 4 }
# hash.extract!(:a, :b) # => {:a=>1, :b=>2}
# hash # => {:c=>3, :d=>4}
def extract!(*keys)
keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
end

View File

@ -388,11 +388,13 @@ class HashExtTest < ActiveSupport::TestCase
def test_extract_nils
original = { a: nil, b: nil }
expected = { a: nil }
remaining = { b: nil }
extracted = original.extract!(:a, :x)
assert_equal expected, extracted
assert_nil extracted[:a]
assert_nil extracted[:x]
assert_equal remaining, original
end
def test_except