Skip to content

Commit f2d04fb

Browse files
Merge pull request #7 from Sage/feature_indifferent_bug_fix
added bugfix to indifferent! method
2 parents 7ee7d21 + 1c7c875 commit f2d04fb

2 files changed

Lines changed: 45 additions & 5 deletions

File tree

lib/hash_kit/helper.rb

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ class Helper
33

44
#This method is called to make a hash allow indifferent access (it will accept both strings & symbols for a valid key).
55
def indifferent!(hash)
6+
unless hash.is_a?(Hash)
7+
return
8+
end
9+
610
#set the default proc to allow the key to be either string or symbol if a matching key is found.
711
hash.default_proc = proc do |h, k|
812
if h.key?(k.to_s)
@@ -16,14 +20,32 @@ def indifferent!(hash)
1620

1721
#recursively process any child hashes
1822
hash.each do |key,value|
19-
if hash[key] != nil && hash[key].is_a?(Hash)
20-
indifferent(hash[key])
23+
if hash[key] != nil
24+
if hash[key].is_a?(Hash)
25+
indifferent!(hash[key])
26+
elsif hash[key].is_a?(Array)
27+
indifferent_array!(hash[key])
28+
end
2129
end
2230
end
2331

2432
hash
2533
end
2634

35+
def indifferent_array!(array)
36+
unless array.is_a?(Array)
37+
return
38+
end
39+
40+
array.each do |i|
41+
if i.is_a?(Hash)
42+
indifferent!(i)
43+
elsif i.is_a?(Array)
44+
indifferent_array!(i)
45+
end
46+
end
47+
end
48+
2749
#This method is called to convert all the keys of a hash into symbols to allow consistent usage of hashes within your Ruby application.
2850
def symbolize(hash)
2951
{}.tap do |h|

spec/hash_kit/helper_spec.rb

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,16 +335,34 @@
335335
let(:hash) do
336336
{
337337
'key1' => 'value1',
338-
key2: 'value2'
338+
key2: 'value2',
339+
key3: [
340+
{
341+
key4: 'value4',
342+
'key5' => 'value5'
343+
}
344+
],
345+
key6: {
346+
key7: 'value7',
347+
'key8' => 'value8'
348+
}
339349
}
340350
end
341351
it 'should allow access to a string key from a symbol' do
342352
subject.indifferent!(hash)
343-
expect(hash[:key1]).to eq hash['key1']
353+
expect(hash[:key1]).to eq 'value1'
344354
end
345355
it 'should allow access to a symbol key from a string' do
346356
subject.indifferent!(hash)
347-
expect(hash['key2']).to eq hash[:key2]
357+
expect(hash['key2']).to eq 'value2'
358+
end
359+
it 'should allow indifferent access to a key within an array' do
360+
subject.indifferent!(hash)
361+
expect(hash[:key3][0]['key4']).to eq 'value4'
362+
end
363+
it 'should allow indifferent access to a key within an nested hash' do
364+
subject.indifferent!(hash)
365+
expect(hash[:key6]['key7']).to eq 'value7'
348366
end
349367
end
350368
end

0 commit comments

Comments
 (0)