Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Hash#transform_keys

hash.transform_keys {|key| ... } → new_hash
hash.transform_keys(hash2) → new_hash
hash.transform_keys(hash2) {|other_key| ...} → new_hash
hash.transform_keys → new_enumerator

Returns a new Hash object; each entry has:

  • A key provided by the block.

  • The value from self.

An optional hash argument can be provided to map keys to new keys. Any key not given will be mapped using the provided block, or remain the same if no block is given.

Transform keys:

Example
h = {foo: 0, bar: 1, baz: 2}
h1 = h.transform_keys {|key| key.to_s }
h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}

h.transform_keys(foo: :bar, bar: :foo)
#=> {bar: 0, foo: 1, baz: 2}

h.transform_keys(foo: :hello, &:to_s)
#=> {:hello=>0, "bar"=>1, "baz"=>2}

Overwrites values for duplicate keys:

Example
h = {foo: 0, bar: 1, baz: 2}
h1 = h.transform_keys {|key| :bat }
h1 # => {:bat=>2}

Returns a new Enumerator if no block given:

Example
h = {foo: 0, bar: 1, baz: 2}
e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
h1 = e.each { |key| key.to_s }
h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}

Ruby version changes

  1. 3.0
See also #transform_keys! #to_s #to_proc #transform_values also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0