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...
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With