Created
December 1, 2012 20:21
-
-
Save a-chernykh/4184731 to your computer and use it in GitHub Desktop.
HashKeysDumper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashKeysDumper | |
def self.dump(hash) | |
hash.map do |k, v| | |
if v.is_a? Hash | |
keys = dump(v) | |
keys.map { |k1| [k, k1].join('.') } | |
else | |
k.to_s | |
end | |
end.flatten | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'hash_keys_dumper' | |
describe HashKeysDumper do | |
describe '.dump' do | |
subject { described_class.dump(hash) } | |
context 'leaf element' do | |
let(:hash) { { key: 'value' } } | |
it { should == ['key'] } | |
end | |
context '2-level hash' do | |
let(:hash) { { level1: { level2: 'value' } } } | |
it { should == ['level1.level2'] } | |
end | |
context '2-level hash with 2 branches' do | |
let(:hash) { { level1: { level21: 'value1', level22: 'value2' } } } | |
it { should == ['level1.level21', 'level1.level22'] } | |
end | |
context '3-level hash with 3 branches' do | |
let(:hash) { { level1: { level21: 'val', level22: { level31: 'value1', level32: 'value2' } } } } | |
it { should == ['level1.level21', 'level1.level22.level31', 'level1.level22.level32'] } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment