Thursday, 2 April 2015

i18n style hash

def convert_hash(hash, path = "")
hash.each_with_object({}) do |(k, v), ret|
key = path + k
if v.is_a? Hash
ret.merge! convert_hash(v, key + ".")
else
ret[key] = v
end
end
end
my_hash = {'a' =>
{'b' => 'a-b',
'c' => 'a-c',
'd' => {'e' => 'a-d-e'}
},
'f' => 'f'}
data = convert_hash(my_hash)
# => {"a.b"=>"a-b", "a.c"=>"a-c", "a.d.e"=>"a-d-e", "f"=>"f"}
data["a.b"]
# => "a-b"
view raw gistfile1.rb hosted with ❤ by GitHub

No comments:

Post a Comment