Created
September 15, 2019 20:01
-
-
Save emilyst/3fe147d8b2bcaa71fff01295f714afbc to your computer and use it in GitHub Desktop.
Flatten a hash's structure in a somewhat naive way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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