Skip to content

Instantly share code, notes, and snippets.

@emilyst
Created September 15, 2019 20:01
Show Gist options
  • Save emilyst/3fe147d8b2bcaa71fff01295f714afbc to your computer and use it in GitHub Desktop.
Save emilyst/3fe147d8b2bcaa71fff01295f714afbc to your computer and use it in GitHub Desktop.
Flatten a hash's structure in a somewhat naive way
#!/usr/bin/env ruby
class Hash
def mash(prefix=nil)
reduce({}) do |a, (k,v)|
case v
when Hash then a.merge(v.mash(k.to_s + '_'))
else a.merge({ "#{prefix}#{k}" => v })
end
end
end
end
h = { 'a' => { 'b' => 1, 'c' => 2 } }
pp h.mash # {"a_b"=>1, "a_c"=>2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment