Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undoing a zip in Ruby [duplicate]

Tags:

ruby

In Python, I can sort of get the "inverse" of a zip by giving back to zip

a = [1,2,3]
b = [4,5,6]
c = zip(a,b) # [(1,4),(2,5),(3,6)]

If instead I start with c, I can get a and b back using the following

c = [(1,4),(2,5),(3,6)]
a, b = zip(*c)

However, in Ruby, there seems to be only a zip method, and as such I'm not sure I can do this in exactly the same way...

Is there some sort of a similar nice idiom in Ruby for "unzipping" a list of lists?


I realize you could do

c[0].zip(*c[1..-1])

to essentially get semantically the same thing, but it doesn't look quite as intuitive this way...

like image 437
math4tots Avatar asked Mar 12 '14 17:03

math4tots


1 Answers

You can use Array#transpose.

a = [1,2,3]
# => [1,2,3]
b = [4,5,6]
# => [4,5,6]
c = a.zip(b) 
# => [[1,4],[2,5],[3,6]]

d, e = c.transpose
# => [[1,2,3], [4,5,6]]
d
# => [1,2,3]
e
# => [4,5,6]
like image 188
Leo Correa Avatar answered Nov 08 '22 16:11

Leo Correa