Skip to content

Commit

Permalink
Add extra tests to ensure Hash#slice works with an array as a key. #613
Browse files Browse the repository at this point in the history
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
matthewrudy authored and lifo committed Jul 17, 2008
1 parent b3a2ee7 commit 7e8aee7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions activesupport/lib/active_support/core_ext/hash/slice.rb
Expand Up @@ -9,6 +9,11 @@ module Hash #:nodoc:
# end
#
# search(options.slice(:mass, :velocity, :time))
#
# If you have an array of keys you want to limit to, you should splat them:
#
# valid_keys = [:mass, :velocity, :time]
# search(options.slice(*valid_keys))
module Slice
# Returns a new hash with only the given keys.
def slice(*keys)
Expand Down
21 changes: 21 additions & 0 deletions activesupport/test/core_ext/hash_ext_test.rb
Expand Up @@ -292,6 +292,27 @@ def test_slice
assert_equal expected, original
end

def test_slice_with_an_array_key
original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
expected = { [:a, :b] => "an array key", :c => 10 }

# Should return a new hash with only the given keys when given an array key.
assert_equal expected, original.slice([:a, :b], :c)
assert_not_equal expected, original

# Should replace the hash with only the given keys when given an array key.
assert_equal expected, original.slice!([:a, :b], :c)
assert_equal expected, original
end

def test_slice_with_splatted_keys
original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
expected = { :a => 'x', :b => "y" }

# Should grab each of the splatted keys.
assert_equal expected, original.slice(*[:a, :b])
end

def test_indifferent_slice
original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
expected = { :a => 'x', :b => 'y' }.with_indifferent_access
Expand Down

0 comments on commit 7e8aee7

Please sign in to comment.