Skip to content

Instantly share code, notes, and snippets.

@jacobvosmaer
Created February 24, 2014 13:19
Show Gist options
  • Save jacobvosmaer/9188280 to your computer and use it in GitHub Desktop.
Save jacobvosmaer/9188280 to your computer and use it in GitHub Desktop.
Hash flattener for Ruby
class Flattener
def initialize(separator='_')
@separator = separator
end
def flatten(hash, prefix=nil)
Enumerator.new do |yielder|
hash.each do |key, value|
raise "Bad key: #{key.inspect}" unless key.is_a?(String)
key = [prefix, key].join(@separator) if prefix
if value.is_a?(Hash)
flatten(value, key).each do |nested_key_value|
yielder.yield nested_key_value
end
else
yielder.yield [key, value]
end
end
end
end
end
require 'rspec'
describe Flattener do
let(:input_hash) do
{
'key1' => :value1,
'nested' => {
'key2' => :value2,
'nested2' => {
'key3' => :value3
}
},
'key4' => :value4
}
end
let(:flattener) { Flattener.new }
subject { flattener.flatten(input_hash).to_a }
specify { expect(subject[0]).to eq(['key1', :value1]) }
specify { expect(subject[1]).to eq(['nested_key2', :value2]) }
specify { expect(subject[2]).to eq(['nested_nested2_key3', :value3]) }
specify { expect(subject[3]).to eq(['key4', :value4]) }
end
require 'pp'
example_hash = {'key1' => :value1, 'nested' =>{'key2' => :value2, 'nested2' => {'key3' => :value3}}, 'key4' => :value4}
pp example_hash
pp Hash[Flattener.new.flatten(example_hash).to_a]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment