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]
|
# valid_keys = [:mass, :velocity, :time]
|
||||||
# search(options.slice(*valid_keys))
|
# search(options.slice(*valid_keys))
|
||||||
def slice(*keys)
|
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)
|
||||||
hash = self.class.new
|
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
|
||||||
keys.each { |k| hash[k] = self[k] if has_key?(k) }
|
|
||||||
hash
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# Replaces the hash with only the given keys.
|
# Replaces the hash with only the given keys.
|
||||||
# Returns a hash contained the removed key/value pairs
|
# Returns a hash contained the removed key/value pairs
|
||||||
# {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}
|
# {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}
|
||||||
def slice!(*keys)
|
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)
|
omit = slice(*self.keys - keys)
|
||||||
hash = slice(*keys)
|
hash = slice(*keys)
|
||||||
replace(hash)
|
replace(hash)
|
||||||
|
@ -33,8 +31,6 @@ class Hash
|
||||||
# Removes and returns the key/value pairs matching the given 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}
|
||||||
def extract!(*keys)
|
def extract!(*keys)
|
||||||
result = {}
|
keys.each_with_object({}) {|key, result| result[key] = delete(key) }
|
||||||
keys.each {|key| result[key] = delete(key) }
|
|
||||||
result
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -486,6 +486,13 @@ class HashExtTest < ActiveSupport::TestCase
|
||||||
assert_equal 'bender', slice['login']
|
assert_equal 'bender', slice['login']
|
||||||
end
|
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
|
def test_except
|
||||||
original = { :a => 'x', :b => 'y', :c => 10 }
|
original = { :a => 'x', :b => 'y', :c => 10 }
|
||||||
expected = { :a => 'x', :b => 'y' }
|
expected = { :a => 'x', :b => 'y' }
|
||||||
|
|
Loading…
Reference in a new issue