Skip to content

Instantly share code, notes, and snippets.

@turlockmike
Created September 10, 2014 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turlockmike/f50e39226fc3e4c74f23 to your computer and use it in GitHub Desktop.
Save turlockmike/f50e39226fc3e4c74f23 to your computer and use it in GitHub Desktop.
Transform Values in a nested hash
class Hash
def self.transform_values(node,&block)
if node.class == Hash
Hash[node.map{|k,v| [k,Hash.transform_values(v, &block)]}]
else
block.call(node)
end
end
def transform_values(&block)
Hash.transform_values(self, &block)
end
end
#Allows you to transform values in a nested hash
# {:a => 1, :b => {:c => 2}}.transform_values {|val| val + 1}
#=> {:a => 2, :b => {:c => 3}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment