Skip to content

Instantly share code, notes, and snippets.

@chris
Created September 20, 2016 19:08
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 chris/b4138603a8fe17e073c6bc073eb17785 to your computer and use it in GitHub Desktop.
Save chris/b4138603a8fe17e073c6bc073eb17785 to your computer and use it in GitHub Desktop.
A "deep" version of Rails' Hash#transform_values
class Hash
class Hash
def deep_transform_values(&block)
reduce({}) do |result, (k, v)|
result[k] = v.is_a?(Hash) ? v.deep_transform_values(&block) : yield(v)
result
end
end
end
end
@roodion
Copy link

roodion commented Aug 28, 2017

Hola, i have a question for you.

I've implemented it while ago as

class Hash

  def deep_transform_values(&block)
    self.transform_values do |value|
      value.is_a?(Hash) ? value.deep_transform_values(&block) : yield(value)
    end
  end

end

i'm not sure what solution is clearer. why do you use reduce for that? Both solutions create new copy of hash..

@halilim
Copy link

halilim commented Jul 19, 2018

To anyone else who reaches this page: v can be an array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment