Skip to content

Commit

Permalink
add more testcases and doc about Hash#extract!
Browse files Browse the repository at this point in the history
  • Loading branch information
mikdiet committed Oct 7, 2012
1 parent 5d27338 commit a4b1196
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
4 changes: 2 additions & 2 deletions activesupport/CHANGELOG.md
@@ -1,12 +1,12 @@
## Rails 4.0.0 (unreleased) ##

* Hash#extract! returns only those keys that present in the reciever.
* Hash#extract! returns only those keys that present in the receiver.

{:a => 1, :b => 2}.extract!(:a, :x) # => {:a => 1}

*Mikhail Dieterle*

* Hash#extract! returns the same subclass, that the reciever is. I.e.
* Hash#extract! returns the same subclass, that the receiver is. I.e.
HashWithIndifferentAccess#extract! returns HashWithIndifferentAccess instance.

*Mikhail Dieterle*
Expand Down
11 changes: 9 additions & 2 deletions activesupport/test/core_ext/hash_ext_test.rb
Expand Up @@ -724,8 +724,10 @@ def test_indifferent_slice_access_with_symbols
def test_extract
original = {:a => 1, :b => 2, :c => 3, :d => 4}
expected = {:a => 1, :b => 2}
remaining = {:c => 3, :d => 4}

assert_equal expected, original.extract!(:a, :b, :x)
assert_equal remaining, original
end

def test_extract_nils
Expand All @@ -739,10 +741,15 @@ def test_extract_nils
end

def test_indifferent_extract
original = {:a => 1, :b => 2, :c => 3, :d => 4}.with_indifferent_access
original = {:a => 1, 'b' => 2, :c => 3, 'd' => 4}.with_indifferent_access
expected = {:a => 1, :b => 2}.with_indifferent_access
remaining = {:c => 3, :d => 4}.with_indifferent_access

assert_equal expected, original.extract!(:a, :b)
[['a', 'b'], [:a, :b]].each do |keys|
copy = original.dup
assert_equal expected, copy.extract!(*keys)
assert_equal remaining, copy
end
end

def test_except
Expand Down
12 changes: 10 additions & 2 deletions guides/source/active_support_core_extensions.md
Expand Up @@ -2867,8 +2867,16 @@ The method `extract!` removes and returns the key/value pairs matching the given

```ruby
hash = {:a => 1, :b => 2}
rest = hash.extract!(:a) # => {:a => 1}
hash # => {:b => 2}
rest = hash.extract!(:a, :x) # => {:a => 1} # non-existing keys are ignored
hash # => {:b => 2}
```

The method `extract!` returns the same subclass of Hash, that the receiver is.

```ruby
hash = {:a => 1, :b => 2}.with_indifferent_access
rest = hash.extract!(:a).class
# => ActiveSupport::HashWithIndifferentAccess
```

NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
Expand Down

0 comments on commit a4b1196

Please sign in to comment.