DEV Community


Convert Rows to Columns with Ruby's Transpose Method

meaganewaller profile image Meagan Waller Originally published at ・2 min read

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.

def rows
Enter fullscreen mode Exit fullscreen mode

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

def columns
  [@spaces[0], @spaces[3], @spaces[6],
   @spaces[1], @spaces[4], @spaces[7],
   @spaces[2], @spaces[5], @spaces[8]]
Enter fullscreen mode Exit fullscreen mode

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

def columns
Enter fullscreen mode Exit fullscreen mode

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.

def winning_solutions
  winning_solutions = [] { |row| winning_solutions << row } { |col| winning_solutions << col }
  winning_solutions << diagonal_ltr
  winning_solutions << diagonal_rtl

def diagonal_ltr
  [@spaces[0], @spaces[4], @spaces[8]]

def diagonal_rtl
  [@spaces[2], @spaces[4], @spaces[6]]
Enter fullscreen mode Exit fullscreen mode

(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.

Discussion (0)

Editor guide