Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created August 22, 2012 05:38
Show Gist options
  • Save ryanlecompte/3422573 to your computer and use it in GitHub Desktop.
Save ryanlecompte/3422573 to your computer and use it in GitHub Desktop.
Hash#smash
class Hash
def smash(prefix = nil)
inject({}) do |acc, (k, v)|
key = prefix.to_s + k
if Hash === v
acc.merge(v.smash(key + '-'))
else
acc.merge(key => v)
end
end
end
end
hash = {
'f' => 100,
'z' => {'j' => 25},
'a' => {'b' => {'c' => 1}}
}
puts hash.smash # => {"f"=>100, "z-j"=>25, "a-b-c"=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment