From: "Jesús Gabriel y Galán" Date: 2013-01-31T19:25:28+09:00 Subject: Re: Select "columns" from multidimensional array? On Thu, Jan 31, 2013 at 10:46 AM, Joel Pearson wrote: > There's probably a simpler answer to this than the ways I've come up > with. > What's the best way to select columns from a two-dimensional array? > > I build arrays to match excel-style formatting, like this but larger: > __________________ > > a = [ > [ 'A1', 'A2', 'A3' ], > [ 'B1', 'B2', 'B3' ], > [ 'C1', 'C2', 'C3' ] > ] > > def get_cols (multi_array, headers ) > > indices = [] > headers.each { |val| indices << multi_array[0].index(val) } > indices.compact! > > multi_array.map do |ar| > indices.map { |idx| ar[idx] } > end > > end > > get_cols a, %w(A1 A3) > > => [["A1", "A3"], ["B1", "B3"], ["C1", "C3"]] Is this the desired output? For getting the columns filtering the ones that have a header: def get_cols(multi_array, headers) multi_array.transpose.select {|(header,_)| headers.include? header} end 1.9.2p290 :001 > a = [ 1.9.2p290 :002 > [ 'A1', 'A2', 'A3' ], 1.9.2p290 :003 > [ 'B1', 'B2', 'B3' ], 1.9.2p290 :004 > [ 'C1', 'C2', 'C3' ] 1.9.2p290 :005?> ] 1.9.2p290 :008 > def get_cols(multi_array, headers) 1.9.2p290 :009?> multi_array.transpose.select {|(header,_)| headers.include? header} 1.9.2p290 :010?> end => nil 1.9.2p290 :011 > get_cols a, %w(A1 A3) => [["A1", "B1", "C1"], ["A3", "B3", "C3"]] Jesus.