Reason #156 • June 5th, 2026

Creating hashes from arrays with Array#to_h

The Array#to_h method provides a convenient way to convert an array of key-value pairs into a hash:

Ruby
array = [["id", 1], ["age", 30], ["name", "Alice"]]

hash = array.to_h
# => {"id" => 1, "age" => 30, "name" => "Alice"}
    

By passing a block returning a two-element array we can convert any array into a hash:

Ruby
users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
]
users_by_id = users.to_h { |user| [user[:id], user] }
# => {1 => {id: 1, name: "Alice"}, 2 => {id: 2, name: "Bob"}}
    

This is commonly used in conjunction with Enumerable methods which return arrays of key-value pairs:

Ruby
users = [
  { id: 1, age: 30, name: "Alice" },
  { id: 2, age: 24, name: "Bob" },
]

user_id_to_name = users.map { |user| [user[:id], user[:name]] }.to_h
# => {1 => "Alice", 2 => "Bob"}
    

History

Array#to_h was added in Ruby 2.1, released in 2013, together with Enumerable#to_h, which introduced the common map { ... }.to_h pattern.

Before this, Ruby already had a similar idea in Hash[]. Though this originally only accepted a flat array of alternating keys and values, in Ruby 1.9, released in 2009, it also started to accept an array of pairs.

Ruby 2.0, released in 2013, made to_h a broader convention by adding it to several classes, including Hash, Struct, OpenStruct, NilClass, and ENV.

Ruby 2.6, released in 2018, added the block form used above.

Reason #157 ?