Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Ruby equivalent for Python's "zip" builtin?

Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing?

A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like:

zip(a, b).all? {|pair| pair[0] === pair[1]}

I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop").

like image 441
Eric Naeseth Avatar asked Nov 04 '08 21:11

Eric Naeseth


1 Answers

Ruby has a zip function:

[1,2].zip([3,4]) => [[1,3],[2,4]]

so your code example is actually:

a.zip(b).all? {|pair| pair[0] === pair[1]}

or perhaps more succinctly:

a.zip(b).all? {|a,b| a === b }
like image 180
dgtized Avatar answered Nov 04 '22 16:11

dgtized