Transpose() function in Ruby Programming

RubyServer Side ProgrammingProgramming

The transpose function in Ruby is mainly used to return the transpose of an array or a matrix.

Syntax

array.transpose

Or

Matrix.transpose

Let's take a couple of examples of the transpose function on array first and then on matrices.

Example 1

Consider the code shown below

# transpose() in array

# array declaration
first_arr = [[18, 22], [33, 3], [8, 6]]

# array declaration
second_arr = [[1, 3, 2, 5, 88, 9]]

# print statements
puts "transpose() output :
#{first_arr.transpose()}\n\n"

puts "transpose() output :
#{second_arr.transpose()}\n\n"

Output

transpose() output : [[18, 33, 8], [22, 3, 6]]
transpose() output : [[1], [3], [2], [5], [88], [9]]

Example 2

# transpose() in array

# array declaration
first_arr = [["xyz", "nil", "cat"]]

# array declaration
second_arr = [["donkey", "go", "lion"]]

# print statements
puts "transpose() output :
#{first_arr.transpose()}\n\n"

puts "transpose() output :
#{second_arr.transpose()}\n\n"

Output

transpose() output : [["xyz"], ["nil"], ["cat"]]
transpose() output : [["donkey"], ["go"], ["lion"]]

Now let's explore a few examples of transpose on matrices.

Example 3

# transpose() in Matrix

require "matrix"

# Initializing matrix
matOne = Matrix[[5, 11], [1, 9]]

# Prints the transpose matrix
puts matOne.transpose()

Output

Matrix[[5, 1], [11, 9]]

Example 4

# transpose() in matrix

require "matrix"

# Initializing matrix
matOne = Matrix[[1, 2], [6, 3], [4, 2]]

# Printing matrix
puts matOne.transpose()

Output

Matrix[[1, 6, 4], [2, 3, 2]]
raja
Updated on 25-Jan-2022 11:12:23

Advertisements