Ruby 程式設計中的 Transpose() 函式


Ruby 語言中 transpose 函式主要用於返回陣列或矩陣的轉置。

語法

array.transpose

Matrix.transpose

我們先舉幾個陣列中 transpose  函式的示例,然後再舉幾個矩陣中的示例。

示例 1

考慮以下所示程式碼

# 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()}

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

"

輸出

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

示例 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()}

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

"

輸出

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

現在讓我們探討幾個矩陣上的轉置示例。

示例 3

# transpose() in Matrix

require "matrix"

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

# Prints the transpose matrix
puts matOne.transpose()

輸出

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

示例 4

# transpose() in matrix

require "matrix"

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

# Printing matrix
puts matOne.transpose()

輸出

Matrix[[1, 6, 4], [2, 3, 2]]

更新於: 2022-01-25

320 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.