Reason #113 • April 23rd, 2026

Combining arrays with Array#zip

Yesterday we looked at Array#transpose. Another useful method when dealing with columnar data, or just parallel arrays, is Array#zip, which combines multiple arrays into a two-dimensional array of rows:

Ruby
days = %w[Mon Tue Wed]
highs = [18, 21, 19]
conditions = ["sunny", "cloudy", "rain"]

forecast_rows = days.zip(highs, conditions)
# => [
#   ["Mon", 18, "sunny"],
#   ["Tue", 21, "cloudy"],
#   ["Wed", 19, "rain"]
# ]

headers = %i[name language city]
values = ["David", "Ruby", "Stockholm"]

headers.zip(values).to_h
# => { name: "David", language: "Ruby", city: "Stockholm" }
      
JavaScript
const days = ["Mon", "Tue", "Wed"];
const highs = [18, 21, 19];
const conditions = ["sunny", "cloudy", "rain"];

const forecastRows = days.map((day, index) => [
  day,
  highs[index],
  conditions[index],
]);
// => [
//   ["Mon", 18, "sunny"],
//   ["Tue", 21, "cloudy"],
//   ["Wed", 19, "rain"]
// ]

const headers = ["name", "language", "city"];
const values = ["David", "Ruby", "Stockholm"];

Object.fromEntries(
  headers.map((header, index) => [header, values[index]])
);
// => { name: "David", language: "Ruby", city: "Stockholm" }
      

As you can see, it also plays nicely with #to_h for building hashes from pairs of arrays.

History

Array#zip arrived in Ruby 1.8.0, released in 2003.

The operation itself is a familiar one from the broader functional programming world, where "zip" has long been the standard name for combining sequences position by position.

Reason #114 ?