Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple arrays of the same size in ruby

Tags:

arrays

ruby

If I have 3 or more arrays I want to combine into one, how do I do that in ruby? Would it be a variation on zip?

For example, I have

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

and I would like to have an array that looks like

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

like image 655
Sharon Yang Avatar asked Feb 13 '23 13:02

Sharon Yang


2 Answers

[a,b,c].transpose

is all you need. I prefer this to zip 50% of the time.

like image 167
Cary Swoveland Avatar answered Feb 15 '23 03:02

Cary Swoveland


I would use Array#zip as below:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
a.zip(b, c)
#=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
like image 44
bjhaid Avatar answered Feb 15 '23 03:02

bjhaid