Permalink
Browse files

fix Hash#slice to not explode on missing keys

  • Loading branch information...
1 parent 0f9fed8 commit 1107d85931a447aa50ab78f8802e4c46e1391995 Sven Fuchs committed Apr 10, 2012
Showing with 16 additions and 4 deletions.
  1. +1 −1 Gemfile.lock
  2. +1 −1 lib/hashr/core_ext/ruby/hash.rb
  3. +14 −2 test/core_ext_test.rb
View
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
- hashr (0.0.19)
+ hashr (0.0.20)
GEM
remote: http://rubygems.org/
@@ -1,7 +1,7 @@
class Hash
def slice(*keep_keys)
h = {}
- keep_keys.each { |key| h[key] = fetch(key) }
+ keep_keys.each { |key| h[key] = fetch(key) if key?(key) }
h
end unless Hash.method_defined?(:slice)
View
@@ -1,16 +1,28 @@
require 'test_helper'
class CoreExtTest < Test::Unit::TestCase
- test 'deep_symbolize_keys walks arrays, too' do
+ test 'Hash#deep_symbolize_keys walks arrays, too' do
hash = { 'foo' => [{ 'bar' => 'bar', 'baz' => { 'buz' => 'buz' } }] }
expected = { :foo => [{ :bar => 'bar', :baz => { :buz => 'buz' } }] }
assert_equal expected, hash.deep_symbolize_keys
end
- test 'deep_symbolize_keys! replaces with deep_symbolize' do
+ test 'Hash#deep_symbolize_keys! replaces with deep_symbolize' do
hash = { 'foo' => { 'bar' => 'baz' } }
expected = { :foo => { :bar => 'baz' } }
hash.deep_symbolize_keys!
assert_equal expected, hash
end
+
+ test 'Hash#slice returns a new hash containing the given keys' do
+ hash = { :foo => 'foo', :bar => 'bar', :baz => 'baz' }
+ expected = { :foo => 'foo', :bar => 'bar' }
+ assert_equal expected, hash.slice(:foo, :bar)
+ end
+
+ test 'Hash#slice does not explode on a missing key' do
+ hash = {}
+ expected = {}
+ assert_equal expected, hash.slice(:foo)
+ end
end

0 comments on commit 1107d85

Please sign in to comment.