Skip to content

Instantly share code, notes, and snippets.

@tadman
Created September 10, 2014 19:33
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 tadman/76bce0174a4ab6b73440 to your computer and use it in GitHub Desktop.
Save tadman/76bce0174a4ab6b73440 to your computer and use it in GitHub Desktop.
Hash#transform_values
class Hash
def transform_values(recursive = true, &block)
Hash[
map do |k, v|
[
k,
(v.is_a?(Hash) && recursive) ? v.transform_values(&block) : yield(v)
]
end
]
end
def transform_values!(recursive = true, &block)
each do |k, v|
self[k] = (v.is_a?(Hash) && recursive) ? v.transform_values(&block) : yield(v)
end
end
end
r = {:a => 1, :b => {:c => 2}}.freeze
puts r.transform_values {|val| val + 1}.inspect
#=> {:a => 2, :b => {:c => 3}}
h = {:a => 1, :b => {:c => 2}}
h.transform_values! {|val| val + 1}
puts h.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment