Reshaping Data with Ruby's Transpose: Rows to Columns

Get ready to uncover a hidden gem in the Ruby toolbox: the transpose method. In this blog post, we delve into the intriguing world of data reshaping, where transpose shines as a powerful tool. Join me on a journey through a real-world example from my software apprenticeship, where I leveraged this method to solve a tic-tac-toe puzzle. By seamlessly transforming rows into columns, transpose proves to be a game-changer for data manipulation and complex operations.

The first time I used the transpose method, I was solving a particular problem. I was creating a tic-tac-toe game during my software apprenticeship. I had split up the game into a few classes. I had a class called Board that represented the tic-tac-toe board and was responsible for holding the board's state after each move. The Board class was initialized with an array called spaces to represent the board's spaces; the default was an array with nine spaces [0, 1, 2, 3, 4, 5, 6, 7, 8] . I had a method that would return the rows named rows.

ruby
1def rows
2  [@spaces[0..2],
3   @spaces[3..5],
4   @spaces[6..8]]
5end

I also needed a method to give me the columns. I could have written something like this.

ruby
1def columns
2  [@spaces[0], @spaces[3], @spaces[6],
3   @spaces[1], @spaces[4], @spaces[7],
4   @spaces[2], @spaces[5], @spaces[8]]
5end

But instead, my method took advantage of Ruby's transpose method.

ruby
1def columns
2  rows.transpose
3end

Transpose turned my rows into columns, and this was a fair use case for this because I was able to create a method that held all the possible winning solutions for a game. You win by getting your marker in 3 consecutive spaces in tic-tac-toe, either across a row, a column or diagonally.

ruby
1def winning_solutions
2  winning_solutions = []
3  rows.map { |row| winning_solutions << row }
4  columns.map { |col| winning_solutions << col }
5  winning_solutions << diagonal_ltr
6  winning_solutions << diagonal_rtl
7end
8
9def diagonal_ltr
10  [@spaces[0], @spaces[4], @spaces[8]]
11end
12
13def diagonal_rtl
14  [@spaces[2], @spaces[4], @spaces[6]]
15end

(Disclaimer for the above code: I wrote this code only months into my software journey, I would do things differently now.) Transposing is perfect when you have a grid and want to transform the rows into columns for easy access.

Avatar for Meagan Waller

Hey hey! 👋

I'm , lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et