jhlu87
jhlu87

Reputation: 4019

ruby/rails how to insert column into multidimensional array

I have an array arr = [[1,2],[3,4]] and a column col = [5,6]

Is there an easy way to get an output of [[1,2,5],[3,4,6]] without looping? Thanks

Upvotes: 3

Views: 943

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29389

Yes, using Array#transpose as follows:

arr = [[1,2],[3,4]]
col = [5,6]
pp (arr.transpose << col).transpose # => [[1, 2, 5], [3, 4, 6]]

Upvotes: 5

Related Questions