Ruby 2.5 adds Hash#transform_keys method

Prathamesh Sonpatki

By Prathamesh Sonpatki

on January 9, 2018

This blog is part of our  Ruby 2.5 series.

Ruby 2.4 added Hash#transform_values method to transform values of the hash.

In Ruby 2.5, a similar method Hash#transform_keys is added for transforming keys of the hash.

1>> h = { name: "John", email: "john@example.com" }
2=> {:name=>"John", :email=>"john@example.com"}
3
4>> h.transform_keys { |k| k.to_s }
5=> {"name"=>"John", "email"=>"john@example.com"}

The bang sibling of this method, Hash#transform_keys! is also added which changes the hash in place.

These two methods are already present in Active Support from Rails and are natively supported in Ruby now.

Rails master is already supporting using the native methods if supported by the Ruby version.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.