Created
September 10, 2014 19:33
-
-
Save tadman/76bce0174a4ab6b73440 to your computer and use it in GitHub Desktop.
Hash#transform_values
This file contains hidden or 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 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