Ruby Array.zip

Learned a neat little trick today:

>>arr1 = [1, 2, 3, 4]
>>arr2 = [5, 6, 7, 8]
>>arr1.zip(arr2)
=> [[1,5],[2,6],[3,7],[4,8]]

Made me smile. It turns out you can use this to iterate over two arrays at the same time and execute a block of code. In JavaScript I’ve gotten used to using a for loop and then indexing using the iterator:

for (i = 0; i < arr.length; i++) {
if arr1[i] == arr2[i]
//do something...
//close brackets etc

But Ruby doesn’t really have a for loop that works that way. Array.zip() to the rescue!

>>arr1.zip(arr2).each do |x, y|
>>if y == x+4
>>puts "awesome!"
>>end
>>end
"awesome"
"awesome"
"awesome"
"awesome"

Leave a Reply

Your email address will not be published. Required fields are marked *