Skip to content
This repository was archived by the owner on Nov 7, 2018. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions lib/nested_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,27 @@ 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
flat_hash
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
Expand Down
4 changes: 2 additions & 2 deletions spec/lib/nested_hash_spec.rb
Original file line number Diff line number Diff line change
@@ -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}}
Expand Down