Skip to content

Instantly share code, notes, and snippets.

@mattpuchlerz
Created March 24, 2009 20:07
Show Gist options
  • Save mattpuchlerz/84340 to your computer and use it in GitHub Desktop.
Save mattpuchlerz/84340 to your computer and use it in GitHub Desktop.
A mapping method for Hash whose behavior is much more in line with Array#map, in that it applies the passed block only to the hash's values, otherwise returning the hash in its original form.
class Hash
def map_values(&block)
Hash[*self.map{ |i| i[1] = yield(i[1]); i }.flatten]
end
end
[ 'asdf', 'qwer' ].map{ |val| val * 2 }
# => [ 'asdfasdf', 'qwerqwer' ]
{ :one => 'asdf', :two => 'qwer' }.map{ |val| val * 2 }
# => [ [:one, 'asdfasdf'], [:two, 'qwerqwer'] ]
{ :one => 'asdf', :two => 'qwer' }.map_values{ |val| val * 2 }
# => { :one => 'asdfasdf', :two => 'qwerqwer' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment