/ Tags: RUBY-CODE / Categories: SOLUTIONS

Transpose A 2d Array Matrix In Ruby

Flip a matrix over its diagonal — rows become columns and columns become rows. Ruby’s Array#transpose handles this in one call.

Description

Array#transpose swaps rows and columns of a rectangular 2D array. All inner arrays must have equal length, or IndexError is raised. For non-rectangular (jagged) arrays, use zip with a splat: matrix.first.zip(*matrix[1..]). Common uses: rotating tabular data, converting column-major to row-major layout, and preparing data for CSV output where rows and columns need swapping.

Sample input:

  matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


Sample Output:

  [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Answer

    matrix = [[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]]

    # Built-in transpose
    matrix.transpose
    # => [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

    # Non-square matrix
    [[1, 2, 3], [4, 5, 6]].transpose
    # => [[1, 4], [2, 5], [3, 6]]

    # Jagged array (unequal row lengths) — use zip
    jagged = [[1, 2, 3], [4, 5], [6]]
    jagged.first.zip(*jagged[1..])
    # => [[1, 4, 6], [2, 5, nil], [3, nil, nil]]

    # Rotate 90° clockwise — transpose then reverse each row
    matrix.transpose.map(&:reverse)
    # => [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

    # Rotate 90° counter-clockwise — reverse each row then transpose
    matrix.map(&:reverse).transpose
    # => [[3, 6, 9], [2, 5, 8], [1, 4, 7]]

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More