Reason #112 •
April 22nd, 2026
Array#transpose
Array#transpose turns columns into rows and rows into columns. It is a great way to destructure tabular data.
Ruby
rows = [
["Alice", "Ruby", "Stockholm"],
["Bob", "Rails", "Gothenburg"],
["Carol", "Hanami", "Malmo"]
]
names, favorite_frameworks, cities = rows.transpose
names
# => ["Alice", "Bob", "Carol"]
favorite_frameworks
# => ["Ruby", "Rails", "Hanami"]
cities
# => ["Stockholm", "Gothenburg", "Malmo"]
JavaScript
const rows = [
["Alice", "Ruby", "Stockholm"],
["Bob", "Rails", "Gothenburg"],
["Carol", "Hanami", "Malmo"],
];
const columns = rows[0].map((_, columnIndex) =>
rows.map((row) => row[columnIndex])
);
const [names, favoriteFrameworks, cities] = columns;
console.log(names);
// => ["Alice", "Bob", "Carol"]
console.log(favoriteFrameworks);
// => ["Ruby", "Rails", "Hanami"]
console.log(cities);
// => ["Stockholm", "Gothenburg", "Malmo"]
Handy for transitioning between row-oriented and column-oriented data structures like database rows, CSV rows or matrices.
History
Array#transpose arrived in Ruby 1.8.0, released in 2003.
The name comes straight from linear algebra, where transposing a matrix swaps rows and columns.