Muktadir
Muktadir

Reputation: 303

Select column-wise of a 2d 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-wise. something like that-

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

How can i do that?

Upvotes: 9

Views: 6188

Answers (4)

The short answer:

A_t = A.tranpose
A_t[0]

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118289

Do as below using #transpose method :

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

As per your comment, I would suggest to use Matrix class. Once you will create a Matrix object, you can access the elements of it, row wise or column wise.

require 'matrix'

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

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

Upvotes: 12

An alternative option would be to use 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"]

Could be rolled into a method as needed.

Upvotes: 9

Cary Swoveland
Cary Swoveland

Reputation: 110745

I would use Array#transpose, but here's an alternative using Array#zip:

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

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

If, instead,

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

and you didn't mind altering a, you could do it this way:

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

Upvotes: 1

Related Questions