何階層にも入れ子になっているHashのKeyを'_'で結合してフラットにします。
#!/usr/bin/env ruby
require "awesome_print"
def flatten_key(hash, key = "", result = {})
hash.each do |k, v|
k2 = "#{key} #{k}"
if v.is_a?(Hash)
flatten_key(v, k2, result)
else
result[k2.strip.gsub(" ", "_").to_sym] = v
end
end
result
end
ap flatten_key(
{
studio3104: { sex: "male", age: "young", favorite: { tsukemen: "warito", sushi: "any" } },
kenjiskywalker: { sex: "male", age: "ojisan", },
}
)
{
:studio3104_sex => "male",
:studio3104_age => "young",
:studio3104_favorite_tsukemen => "warito",
:studio3104_favorite_sushi => "any",
:kenjiskywalker_sex => "male",
:kenjiskywalker_age => "ojisan"
}