Created
July 7, 2011 19:56
-
-
Save dbenhur/1070399 to your computer and use it in GitHub Desktop.
Safer deep transform_hash from http://avdi.org/devblog/2009/11/20/hash-transforms-in-ruby/
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
def transform_hash(original, options={}, &block) | |
options[:safe_descent] ||= {} | |
new_hash = {} | |
options[:safe_descent][original.object_id] = new_hash | |
original.inject(new_hash) { |result, (key,value)| | |
if (options[:deep] && Hash === value) | |
value = options[:safe_descent].fetch( value.object_id ) { | |
transform_hash(value, options, &block) | |
} | |
end | |
block.call(result,key,value) | |
result | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment