Skip to content

Instantly share code, notes, and snippets.

@jqr
Created April 8, 2009 02:11
Show Gist options
  • Save jqr/91588 to your computer and use it in GitHub Desktop.
Save jqr/91588 to your computer and use it in GitHub Desktop.
class Hash
# Flattens a hash by joining keys with joiner. Meant for use with String or
# Symbol keys. Resulting hash keys take on the type of the parent key.
#
# { 'a' => { 'b' => 1 } }.flatten_with_joined_keys
# # => {"a_b"=>1}
# { :a => { :b => { :c => { :d => 1 } } } }.flatten_with_joined_keys('')
# # => {:abcd=>1}
def flatten_with_joined_keys(joiner = '_')
output = {}
each do |parent_key, parent_value|
if parent_value.is_a?(Hash)
parent_value.each do |child_key, child_value|
new_key = "#{parent_key}#{joiner}#{child_key}"
new_key = new_key.to_sym if parent_key.is_a?(Symbol)
output[new_key] = child_value
end
else
output[parent_key] = parent_value
end
end
if output.values.detect { |v| v.is_a?(Hash) }
output.flatten_with_joined_keys(joiner)
else
output
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment