Created
November 16, 2015 20:04
-
-
Save adamgotterer/be511f5c1ab4b4f34ad9 to your computer and use it in GitHub Desktop.
Recursively transform the values of a Hash or Array
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
class Hash | |
def deep_transform_values(&block) | |
_deep_transform_values_in_object(self, &block) | |
end | |
def deep_transform_values!(&block) | |
_deep_transform_values_in_object!(self, &block) | |
end | |
private | |
def _deep_transform_values_in_object(object, &block) | |
case object | |
when Hash | |
object.each_with_object({}) do |(key, value), result| | |
result[key] = _deep_transform_values_in_object(value, &block) | |
end | |
when Array | |
object.map {|e| _deep_transform_values_in_object(e, &block) } | |
else | |
yield(object) | |
end | |
end | |
def _deep_transform_values_in_object!(object, &block) | |
case object | |
when Hash | |
object.each do |key, value| | |
object[key] = _deep_transform_values_in_object!(value, &block) | |
end | |
when Array | |
object.map! {|e| _deep_transform_values_in_object!(e, &block) } | |
else | |
yield(object) | |
end | |
end | |
end | |
hash = { a: 1, b: { c: 2 }, d: [1,2,3]} | |
hash1 = { a: 1, b: 2} | |
puts hash.deep_transform_values { |val| val.to_s } | |
puts hash.deep_transform_values! { |val| val.to_s } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment