1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

add more testcases and doc about Hash#extract!

This commit is contained in:
Mikhail Dieterle 2012-09-21 11:43:59 +03:00
parent 5d27338ab0
commit a4b1196163
3 changed files with 21 additions and 6 deletions

View file

@ -1,12 +1,12 @@
## Rails 4.0.0 (unreleased) ## ## 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} {:a => 1, :b => 2}.extract!(:a, :x) # => {:a => 1}
*Mikhail Dieterle* *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. HashWithIndifferentAccess#extract! returns HashWithIndifferentAccess instance.
*Mikhail Dieterle* *Mikhail Dieterle*

View file

@ -724,8 +724,10 @@ class HashExtTest < ActiveSupport::TestCase
def test_extract def test_extract
original = {:a => 1, :b => 2, :c => 3, :d => 4} original = {:a => 1, :b => 2, :c => 3, :d => 4}
expected = {:a => 1, :b => 2} expected = {:a => 1, :b => 2}
remaining = {:c => 3, :d => 4}
assert_equal expected, original.extract!(:a, :b, :x) assert_equal expected, original.extract!(:a, :b, :x)
assert_equal remaining, original
end end
def test_extract_nils def test_extract_nils
@ -739,10 +741,15 @@ class HashExtTest < ActiveSupport::TestCase
end end
def test_indifferent_extract 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 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 end
def test_except def test_except

View file

@ -2867,10 +2867,18 @@ The method `extract!` removes and returns the key/value pairs matching the given
```ruby ```ruby
hash = {:a => 1, :b => 2} hash = {:a => 1, :b => 2}
rest = hash.extract!(:a) # => {:a => 1} rest = hash.extract!(:a, :x) # => {:a => 1} # non-existing keys are ignored
hash # => {:b => 2} 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`. NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
### Indifferent Access ### Indifferent Access