Reputation: 227
For an array that looks like:
arr = [["name1","name2","name3"],["address1","address2","address3"],["phone1","phone2","phone3"]]
I would like to re-arrange it so that it looks like:
arr = [["name1","address1","phone1"],["name2","address2","phone2"], ...
Current method is:
name = arr[0]
add = arr[1]
phone = arr[2]
arr = name.zip(add,phone)
which works, but when I have over ten nested arrays within an array, I have ten lines of defining which is which, just to use zip later.
I hope someone can show me a better way of handling this.
EDIT:
I originally had "Phone1","Phone2", as my initial array (uppercase) and "phone1", "phone2" as my transposed array.
This wasn't intended so I edited it, but with my original post Sawa's answer handles the transpose & the UPPERCASE to lowercase.
Also found the documentation here:
http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-transpose
Upvotes: 2
Views: 75
Reputation: 168101
An answer to the original question:
arr.transpose.map{|a| a.map(&:downcase)}
An answer to a different question after OP's edit:
arr.transpose
Upvotes: 3
Reputation: 37409
How about:
arr = arr.shift.zip(*arr)
this code uses the first element of the arr
while removing it from arr
(via shift
), than it uses the splat
operator to zip it with the rest of the arrays in the array.
Upvotes: 1