Home » Ruby programming

Array.transpose Method with Example in Ruby

Ruby Array.transpose Method: Here, we are going to learn about the Array.transpose Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 12, 2020

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.

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.

Syntax:

    array_instance.transpose -> new_array

Argument(s) required:

This method does not take any argument.

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

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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.