Skip to content

Instantly share code, notes, and snippets.

@rhenning
Created April 6, 2016 01:23
Show Gist options
  • Save rhenning/5f262a0de5ec04615a244378c7d722b8 to your computer and use it in GitHub Desktop.
Save rhenning/5f262a0de5ec04615a244378c7d722b8 to your computer and use it in GitHub Desktop.
naive nested ruby hash flattener
class FlatHash
def self.flatten_hval(pre, val)
out = {}
val.each do |k, v|
out["#{pre}_#{k}"] = v
end
flatten(out)
end
def self.flatten_aval(pre, val)
out = {}
val.each_with_index do |v, i|
case v
when String, Symbol, Numeric
out["#{pre}_#{i}"] = v.to_s
else
raise TypeError, "String, Symbol or Numeric required. Got #{v.class}"
end
end
out
end
def self.flatten(hash)
out = {}
hash.each do |k, v|
case v
when String, Symbol, Numeric
out[k.to_s] = v.to_s
when Array
out.merge!(flatten_aval(k, v))
when Hash
out.merge!(flatten_hval(k, v))
end
end
out
end
end
require 'minitest/autorun'
class TestFlatHash < MiniTest::Test
def test_it_flattens
i1 = {
this: {
that: {
other: 'thing',
bibbity: {
bobbity: {
boo: :foo!
}
}
}
},
foo: ['bar', 'baz', 'biddy'],
boom: 'bip',
tech: 9
}
o1 = {
'this_that_bibbity_bobbity_boo' => 'foo!',
'this_that_other' => 'thing',
'foo_0' => 'bar',
'foo_1' => 'baz',
'foo_2' => 'biddy',
'boom' => 'bip',
'tech' => '9'
}
assert_equal o1, FlatHash.flatten(i1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment