Skip to content

Instantly share code, notes, and snippets.

@hyeomans
Created April 26, 2013 23:53
Show Gist options
  • Save hyeomans/5471206 to your computer and use it in GitHub Desktop.
Save hyeomans/5471206 to your computer and use it in GitHub Desktop.
# check the comments for @billmann's awesome solution to the same problem
def make_hash_one_dimensional(input = {}, output = {}, options = {})
input.each do |key, value|
key = options[:prefix].nil? ? "#{key}" : "#{options[:prefix]}#{options[:delimiter]||"_"}#{key}"
if value.is_a? Hash
make_hash_one_dimensional(value, output, :prefix => key, :delimiter => "_")
else
output[key] = value
end
end
output
end
nested_hash = {:a => {:b => {:c => {:d => {:e => "hi"}}}}, :f => "there"}
make_hash_one_dimensional(nested_hash)
#=> {"f"=>"there", "a_b_c_d_e"=>"hi"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment