From 53d5c805773c95365adb917d18413196a3a71a25 Mon Sep 17 00:00:00 2001 From: Josh Owens Date: Sun, 13 Jul 2008 10:59:29 -0400 Subject: [PATCH] Making slice work with an array of keys. --- .../lib/active_support/core_ext/hash/slice.rb | 1 + activesupport/test/core_ext/hash_ext_test.rb | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 0 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb index be4dec6..d3837d2 100644 --- a/activesupport/lib/active_support/core_ext/hash/slice.rb +++ b/activesupport/lib/active_support/core_ext/hash/slice.rb @@ -12,6 +12,7 @@ module ActiveSupport #:nodoc: module Slice # Returns a new hash with only the given keys. def slice(*keys) + keys.flatten! keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) hash = {} keys.each { |k| hash[k] = self[k] if has_key?(k) } diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 69028a1..35b2ca4 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -281,6 +281,20 @@ class HashExtTest < Test::Unit::TestCase assert_equal expected, original.slice!(:a, :b) assert_equal expected, original 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 original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access -- 1.5.4.4