diff --git a/lib/nested_hash.rb b/lib/nested_hash.rb index fd9eb4c3..48574b7e 100644 --- a/lib/nested_hash.rb +++ b/lib/nested_hash.rb @@ -25,11 +25,11 @@ def add(hash) # generate a flat, non-nested hash # with keys that have dots representing the hierarchy def withdotkeys(deep_hash = self, flat_hash = {}, root = '') - deep_hash.each do |key, value| - if deep_hash[key].is_a?(Hash) + deep_hash.each do |k, value| + key = root + k + if value.is_a?(Hash) flat_hash.merge! withdotkeys(value, flat_hash, key + '.') else - key = "#{root}#{key}" if not root.empty? flat_hash[key] = value end end @@ -37,15 +37,15 @@ def withdotkeys(deep_hash = self, flat_hash = {}, root = '') end # generate a list of the keys with dots representing the hierarchy - def dotkeys(row = self, prefix = '', path = []) + def dotkeys(row = self, prefix = '') human_names = [] - paths = [] - row.keys.each do |key| - if row[key].is_a?(Hash) - new_human_names = dotkeys(row[key], key + '.') - human_names += new_human_names + row.keys.each do |k| + key = prefix + k + if row[k].is_a?(Hash) + new_human_names = dotkeys(row[k], key + '.') + human_names += new_human_names else - human_names << prefix + key + human_names << key end end human_names diff --git a/spec/lib/nested_hash_spec.rb b/spec/lib/nested_hash_spec.rb index da234581..e3364345 100644 --- a/spec/lib/nested_hash_spec.rb +++ b/spec/lib/nested_hash_spec.rb @@ -1,8 +1,8 @@ require 'nested_hash' describe NestedHash do - let(:input) { {"loc.x" => 1, "loc.y" => 2, "foo.a" => 10, "foo.b" => 20, "loc.z" => 3}} - let(:expected) {{"loc" => {"x" => 1, "y" => 2, "z" => 3}, "foo" => {"a" => 10, "b" => 20}}} + let(:input) { {"loc.x" => 1, "loc.y" => 2, "foo.a" => 10, "foo.b" => 20, "foo.c.baz" => 3,}} + let(:expected) {{"loc" => {"x" => 1, "y" => 2}, "foo" => {"a" => 10, "b" => 20, "c" => { "baz" => 3}}}} let(:symbol_keys) { {x:1, y:2}} let(:symbol_keys_result) { {'x' => 1, 'y' => 2}}