Skip to content

Instantly share code, notes, and snippets.

@dalazaro
Last active August 17, 2017 15:51
Show Gist options
  • Save dalazaro/b9ca38652eacbcefc602a0007a265bbf to your computer and use it in GitHub Desktop.
Save dalazaro/b9ca38652eacbcefc602a0007a265bbf to your computer and use it in GitHub Desktop.
How to transpose an array!

Ruby Method: Array.transpose

DataType: Array

The Array.transpose method takes in a two-dimensional array (array of arrays), and if each subarray is of equal length, the method will transpose (rearrange) the elements into new subarrays.

Example:

In this array (you could even call it "taco"), we have three subarrays of equal lengths.

taco=[[1, 2], [3, 4], [5, 6]]

If we call taco.transpose, we end up with this new array:

=> [[1, 3, 5], [2, 4, 6]]

The .transpose method made a new subarray that contains just our index [0] elements, and a different subarray for all our index [1] elements.

To think of it another way, it flipped our columns into rows.


So what would happen if we removed 6 from our original taco array?

taco=[[1, 2], [3, 4], [5]]
Answer:

Now that the third subarray has only one element instead of two, our console throws us an IndexError.

IndexError: element size differs (1 should be 2)

This is telling us that our subarrays are unequal length, and the array can't be transposed.


What if we have a 2D array of not just integers, but one that contains different data types?

hotdog=[[1, 2, 3], [4, 5.0, 6], ["sauerkraut", nil, 9]]

Here we have a mix of integers, a float (5.0), a string ("sauerkraut"), and even nil.

What do?

Good news! The console deems that this array is kosher, so we can pass hotdog through the method and end up with:

=> [[1, 4, "sauerkraut"], [2, 5.0, nil], [3, 6, 9]]

Unfortunately, there is no .transpose! (emphasis: bang) method which would save the state of our output into the original variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment