ruby hash transform_values method
with ruby 2.4.0 onwards we have this special method for the ruby hash.
It is transform_values
using this method we can changes the values for a hash without affecting the keys.
hash = { one: 1, two: 2, three: 3 }
# using non ! , create new hash with transformed values
hash.transform_values(&:to_s)
#=> { one: '1', two: '2', three: '3' }
puts hash
#=> { one: 1, two: 2, three: 3 }
# using ! , modify the current hash values itself
hash.transform_values!(&:to_s)
#=> { one: '1', two: '2', three: '3' }
puts hash
#=> { one: '1', two: '2', three: '3' }
but if you are in less than 2.4 version of ruby you might have done similar to below snippet to get it done
hash = { a: 'APPLE', b: 'BOY', c: 'CAT' }
# with inject, non destructive version, creates new hash
transformed_hash =
hash.inject({}) { |h_acc, (key, val)| h_acc[key] = val.downcase; h_acc }
puts hash
#=> {:a=>"APPLE", :b=>"BOY", :c=>"CAT"}
puts transformed_hash
#=> {:a=>"apple", :b=>"boy", :c=>"cat"}
OR
# with each_with_object, non destructive version, creates new hash
transformed_hash =
hash.each_with_object({}) { |(key, val), h_acc| h_acc[key] = val.downcase }
puts hash
#=> {:a=>"APPLE", :b=>"BOY", :c=>"CAT"}
puts transformed_hash
#=> {:a=>"apple", :b=>"boy", :c=>"cat"}
# with each, the destructive version, modify the hash itself
hash.each { |key, val| hash[key] = val.downcase }
puts hash
#=> {:a=>"apple", :b=>"boy", :c=>"cat"}