Select a column from the 2nd array in ruby

I have a 2d array A = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]]. I want to access this array column by column. something like that -

A[all][0]
-> [a1,b1,c1]

How can i do this?

+4
source share
3 answers

Do as below using the method #transpose:

A.transpose.each do |ary|
   # your code
end

According to your comment, I would suggest using a class Matrix. Once you create an object Matrix, you can access its elements, bits, or columns.

require 'matrix'

A = [['a1','a2','a3'],['b1','b2','b3'],['c1','c2','c3']]

mat = Matrix[ *A ]
mat.column(1).to_a # => ["a2", "b2", "c2"]
+9
source

An alternative is to use Array # map :

A = [["a1","a2","a3"],["b1","b2","b3"],["c1","c2","c3"]]
=> [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]]
>> col = 0
=> 0
>> A.map{|a| a[col]}
=> ["a1", "b1", "c1"]

If necessary, can be minimized to a method.

+6
source

Array # transpose, Array #zip:

A = [[1,2,3],[4,5,6],[7,8,9]]

A.first.zip(*A[1..-1]).first #=> [1, 4, 7]

a = [[1,2,3],[4,5,6],[7,8,9]]

a, :

a.shift.zip(*a).first #=> [1, 4, 7]
0

Source: https://habr.com/ru/post/1542243/


All Articles