mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #5287 from nashby/hash-slice-extract
refactor Hash#slice and Hash#extract!
This commit is contained in:
commit
085cb3b9af
2 changed files with 11 additions and 8 deletions
|
@ -13,17 +13,15 @@ class Hash
|
|||
# valid_keys = [:mass, :velocity, :time]
|
||||
# search(options.slice(*valid_keys))
|
||||
def slice(*keys)
|
||||
keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
|
||||
hash = self.class.new
|
||||
keys.each { |k| hash[k] = self[k] if has_key?(k) }
|
||||
hash
|
||||
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
|
||||
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
|
||||
end
|
||||
|
||||
# Replaces the hash with only the given keys.
|
||||
# Returns a hash contained the removed key/value pairs
|
||||
# {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}
|
||||
def slice!(*keys)
|
||||
keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
|
||||
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
|
||||
omit = slice(*self.keys - keys)
|
||||
hash = slice(*keys)
|
||||
replace(hash)
|
||||
|
@ -33,8 +31,6 @@ 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}
|
||||
def extract!(*keys)
|
||||
result = {}
|
||||
keys.each {|key| result[key] = delete(key) }
|
||||
result
|
||||
keys.each_with_object({}) {|key, result| result[key] = delete(key) }
|
||||
end
|
||||
end
|
||||
|
|
|
@ -486,6 +486,13 @@ class HashExtTest < ActiveSupport::TestCase
|
|||
assert_equal 'bender', slice['login']
|
||||
end
|
||||
|
||||
def test_extract
|
||||
original = {:a => 1, :b => 2, :c => 3, :d => 4}
|
||||
expected = {:a => 1, :b => 2}
|
||||
|
||||
assert_equal expected, {:a => 1, :b => 2, :c => 3, :d => 4}.extract!(:a, :b)
|
||||
end
|
||||
|
||||
def test_except
|
||||
original = { :a => 'x', :b => 'y', :c => 10 }
|
||||
expected = { :a => 'x', :b => 'y' }
|
||||
|
|
Loading…
Reference in a new issue