提交 396f9df8 编写于 作者: J Josh Owens 提交者: Joshua Peek

Hash#slice supports an array of keys [#613 state:resolved]

Signed-off-by: NJoshua Peek <josh@joshpeek.com>
上级 7ae2105d
...@@ -12,6 +12,7 @@ module Hash #:nodoc: ...@@ -12,6 +12,7 @@ module Hash #:nodoc:
module Slice module Slice
# Returns a new hash with only the given keys. # Returns a new hash with only the given keys.
def slice(*keys) def slice(*keys)
keys.flatten!
keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
hash = {} hash = {}
keys.each { |k| hash[k] = self[k] if has_key?(k) } keys.each { |k| hash[k] = self[k] if has_key?(k) }
......
...@@ -282,6 +282,20 @@ def test_slice ...@@ -282,6 +282,20 @@ def test_slice
assert_equal expected, original assert_equal expected, original
end end
# This is needed for something like hash.slice!(hash.keys.sort_by {rand} [0..4])
def test_slice_with_array_keys
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x', :b => 'y' }
# Should return a new hash with only the given keys, when given an array of keys.
assert_equal expected, original.slice([:a, :b])
assert_not_equal expected, original
# Should replace the hash with only the given keys, when given an array of keys.
assert_equal expected, original.slice!([:a, :b])
assert_equal expected, original
end
def test_indifferent_slice def test_indifferent_slice
original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
expected = { :a => 'x', :b => 'y' }.with_indifferent_access expected = { :a => 'x', :b => 'y' }.with_indifferent_access
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册