SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Saturday, June 20, 2009

Ruby array transpose

Ruby Arrays are ordered, integer-indexed collections of any objects.In Array transpose assumes the self is an array of arrays and transposes the rows and columns.
a = [[1,2], [3,4], [5,6]]

Now to create array of array its easy to do rails helper in_groups_of

%w(1 2 3 4 5 6 ).in_groups_of(2,false)

[["1", "2"], ["3", "4"], ["5", "6"]]

Note if the array length is odd then try to pass the array with in_groups_of(number,string)
instead of false


Then with ruby we can use some tricky methods.such as shifting the array position.
array=[["1", "2"], ["3", "4"], ["5", "6"]]

array.transpose
[["1", "3", "5"], ["2", "4", "6"]]