简体   繁体   中英

Ruby: match first, second, this etc elements from a dimensional array

I have an array of arrays. I want to concatenate the first, second, third elements of arrays.

Example arrays:

a =  [[4, 5, 6], [1, 2, 3], [8, 9, 10]]
a1 = [[1, 2, 3], [8, 9, 10]]
a2 = [[4, 5, 6], [1, 2, 3], [8, 9, 10], [11, 21, 31]]

Output:

out of a:  [[4,1,8],[5,2,9],[6,3,10]]
out of a1: [[1,8],[2,9],[3,10]]
out of a2: [[4,1,8,11],[5,2,9,21],[6,3,10,31]]

Use transpose method

a.transpose
 => [[4, 1, 8], [5, 2, 9], [6, 3, 10]] 

Array# transpose :

[a, a1, a2].map(&:transpose)
# [
#   [[4, 1, 8], [5, 2, 9], [6, 3, 10]],
#   [[1, 8], [2, 9], [3, 10]],
#   [[4, 1, 8, 11], [5, 2, 9, 21], [6, 3, 10, 31]]
# ]

Whenever Array#transpose can be used so can Enumerable#zip .

a.first.zip *a.drop(1)
  #=> [[4,1,8],[5,2,9],[6,3,10]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM