Вопрос

I am trying to use Enumerable#zip on an array of arrays in order to group the elements of the first nested array with the corresponding elements of each subsequent nested array. This is my array:

roster = [["Number", "Name", "Position", "Points per Game"],
          ["12","Joe Schmo","Center",[14, 32, 7, 0, 23] ],
          ["9", "Ms. Buckets ", "Point Guard", [19, 0, 11, 22, 0] ],
          ["31", "Harvey Kay", "Shooting Guard", [0, 30, 16, 0, 25] ], 
          ["7", "Sally Talls", "Power Forward", [18, 29, 26, 31, 19] ], 
          ["22", "MK DiBoux", "Small Forward", [11, 0, 23, 17, 0] ]]

I want to group "Number" with "12", "9", "31", "7", and "22", and then do the same for "Name", "Position", etc. using zip. The following gives me the output I want:

roster[0].zip(roster[1], roster[2], roster[3], roster[4], roster[5])

How can I reformat this so that if I added players to my roster, they would be automatically included in the zip without me having to manually type in roster[6], roster[7], etc. I've tried using ranges in a number of ways but nothing seems to have worked yet.

Это было полезно?

Решение

First extract the head and tail of the list (header and rows, respectively) using a splat, then zip them together:

header, *rows = roster
header.zip(*rows)

This is the same as using transpose on the original roster:

header, *rows = roster
zipped = header.zip(*rows)

roster.transpose == zipped  #=> true

Другие советы

:zip.to_proc[*roster]

a bit more flexible than transpose:

:zip.to_proc[*[(0..2), [:a, :b, :c]]] #=> [[0, :a], [1, :b], [2, :c]]

p roster.transpose()

.......................

roster[0].zip(*(roster[1..-1]))

Doesn't matter how many are in the roster array.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top