Skip to content

Instantly share code, notes, and snippets.

@lightscalar
Last active December 17, 2015 05:28
Show Gist options
  • Select an option

  • Save lightscalar/5557833 to your computer and use it in GitHub Desktop.

Select an option

Save lightscalar/5557833 to your computer and use it in GitHub Desktop.
Ruby Array Tricks

Suppose you have an array of multiple (i.e., more than two) ruby arrays,

ary = [[1,2,3,4], [4,5,6,7], [8,9,10,11]]

To zip together these arrays in an element-wise fashion, we can use the array's zip method:

zipped_ary = ary[0].zip(*ary.last(ary.size-1)) # => [[1,4,8], [2,5,9], [3,6,10], [4,7,22]]

Not sure if this is easiest way to do this, but cannot seem to find native methods that zip together multiple arrays.

UPDATE

Ah, well, you know what?, there is a way easier way to do this. It turns out, this is simply the transpose of the original 2D array. And ruby let's you do that natively:

ary.transpose # => [[1,4,8], [2,5,9], [3,6,10], [4,7,22]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment