Hash.to_a / Hash[] / transform_keys / transform_values
Methods for converting a hash to an array and for bulk-transforming keys or values. Use transform_keys and transform_values to transform every key or every value while keeping the hash structure intact.
Syntax
# Converts a hash to an array of [key, value] pairs.
hash.to_a
# Creates a hash from an array.
Hash[array]
array.to_h
# Returns a new hash with all keys transformed by the block.
hash.transform_keys { |key| new_key }
# Returns a new hash with all values transformed by the block.
hash.transform_values { |value| new_value }
Method list
| Method | Description |
|---|---|
| to_a | Converts a hash to an array in the format [[key, value], ...]. |
| Hash[array] | Creates a hash from an array in the format [[key, value], ...]. |
| to_h { |k, v| ... } | Creates a hash from an array. You can specify a transformation with a block (Ruby 2.6 and later). |
| transform_keys { |k| ... } | Returns a new hash with all keys transformed (Ruby 2.5 and later). |
| transform_keys! { |k| ... } | Transforms the keys of the original hash in place (destructive). |
| transform_values { |v| ... } | Returns a new hash with all values transformed (Ruby 2.4 and later). |
| transform_values! { |v| ... } | Transforms the values of the original hash in place (destructive). |
| invert | Returns a new hash with keys and values swapped. |
| flatten(depth) | Converts a hash to an array and flattens nested arrays up to the specified depth. |
Sample code
person = { name: 'Taro', age: 30, city: 'Tokyo' }
# to_a: convert a hash to an array
puts person.to_a.inspect
# [[:name, "Taro"], [:age, 30], [:city, "Tokyo"]]
# Create a hash from an array
pairs = [[:x, 1], [:y, 2], [:z, 3]]
puts Hash[pairs].inspect # {:x=>1, :y=>2, :z=>3}
puts pairs.to_h.inspect # {:x=>1, :y=>2, :z=>3} (Ruby 2.0 and later)
# transform_keys: convert symbol keys to strings
string_keys = person.transform_keys(&:to_s)
puts string_keys.inspect
# {"name"=>"Taro", "age"=>30, "city"=>"Tokyo"}
# Convert string keys to uppercase
config = { 'host' => 'localhost', 'port' => '3000' }
puts config.transform_keys(&:upcase).inspect
# {"HOST"=>"localhost", "PORT"=>"3000"}
# transform_values: apply a transformation to all values
prices = { apple: 100, orange: 80, grape: 250 }
with_tax = prices.transform_values { |v| (v * 1.1).round }
puts with_tax.inspect
# {:apple=>110, :orange=>88, :grape=>275}
# invert: swap keys and values
code_map = { ok: 200, not_found: 404, error: 500 }
puts code_map.invert.inspect
# {200=>:ok, 404=>:not_found, 500=>:error}
# zip + to_h: build a hash from two arrays
keys = [:a, :b, :c]
values = [1, 2, 3]
puts keys.zip(values).to_h.inspect # {:a=>1, :b=>2, :c=>3}
Overview
transform_keys and transform_values were added in Ruby 2.4–2.5. Before these methods, map { }.to_h was commonly used as a workaround, but the dedicated methods make the intent clearer and the code more readable.
External data such as JSON often uses string keys, so transform_keys(&:to_sym) is frequently used to convert them to symbols. Note that invert swaps keys and values, but if the values are not unique, only the last key processed is kept and some keys will be lost. Make sure values are unique before using it.
You can pass a block to to_h to perform a mapping at the same time (e.g., array.to_h { |e| [e, e.upcase] }). Combining it with zip lets you concisely build a hash from two parallel arrays.
If you find any errors or copyright issues, please contact us.