Array.transpose方法 (Array.transpose Method)
In this article, we will study about Array.transpose Method. You all must be thinking the method must be doing something related to transposing something. It is not as simple as it looks. Well, we will figure this out in the rest of our content. We will try to understand it with the help of syntax and demonstrating program codes.
在本文中,我们将研究Array.transpose方法 。 你们都必须认为该方法必须在做与移调有关的事情。 它并不像看起来那么简单。 好吧,我们将在其余内容中解决这个问题。 我们将尝试借助语法并演示程序代码来理解它。
Method description:
方法说明:
This method is a public instance method and defined for the Array class in Ruby’s library. This method works in a way that it transposes the objects present in the Array instance. Transposing simply means that the row becomes column and the column becomes a row. For transposing the Array instance, you must remember that all the sub-arrays present in the Array instance should be of the same length. If the size of sub-arrays doesn’t match then the method will provide you an Index Error.
该方法是一个公共实例方法,为Ruby库中的Array类定义。 此方法的工作方式是转置Array实例中存在的对象。 简单地转置意味着行变成列并且列变成行 。 为了转置Array实例,您必须记住Array实例中存在的所有子数组都应具有相同的长度。 如果子数组的大小不匹配,则该方法将为您提供索引错误。
Syntax:
句法:
array_instance.transpose -> new_array
Argument(s) required:
所需参数:
This method does not take any argument.
此方法不带任何参数。
Example 1:
范例1:
=begin
Ruby program to demonstrate transpose method
=end
# array declaration
table = [[2,4,8],[10,12,134],[160,180,200]]
puts "Array transpose implementation"
rslt = table.transpose
puts "The Array instance returned from the method is:#{rslt}"
Output
输出量
Array transpose implementation
The Array instance returned from the method is:[[2, 10, 160], [4, 12, 180], [8, 134, 200]]
Explanation:
说明:
In the above code, you can observe that we are transposing elements in the Array instance with the help of the Array.transpose method. In the output, you can see that the row has changed to the column and the column has changed to row.
在上面的代码中,您可以观察到借助于Array.transpose方法 ,我们正在对Array实例中的元素进行转置。 在输出中,您可以看到该行已更改为列,该列已更改为行。
Example 2:
范例2:
=begin
Ruby program to demonstrate transpose method
=end
# array declaration
table = [[2,4,8],[10,12,134],[160,180,200,344]]
puts "Array transpose implementation"
rslt = table.transpose
puts "The Array instance returned from the method is:#{rslt}"
Output
输出量
Array transpose implementation
element size differs (4 should be 3)
(repl):9:in `transpose'
(repl):9:in `<main>'
Explanation:
说明:
In the above code, you can observe that the method is giving an IndexError because the sub-arrays in the self Array instance are not of the same size or length. Ideally, transposing such Array instances is not possible.
在上面的代码中,您可以观察到该方法给出IndexError,因为self Array实例中的子数组的大小或长度不同。 理想情况下,不可能转置此类Array实例。
翻译自: https://www.includehelp.com/ruby/array-transpose-method-with-example.aspx