← Back to Ruby Course | Chapter 4: Arrays | Lesson 5 of 7

zip

In this page:

  1. zip

zip

zip combines two or more arrays element-by-element into an array of small arrays, pairing up corresponding elements by position, similar to a zipper. If the arrays have different lengths, missing elements from the shorter ones become nil. It's frequently used to iterate over two related arrays together.

Note: array1.zip(array2).each { |a, b| ... } is a common idiom for iterating two arrays together in lockstep.

Example: zip

markup
names = ["Alice", "Bob", "Cara"]
ages = [30, 25, 40]

paired = names.zip(ages)
puts paired.inspect

paired.each { |name, age| puts "#{name} is #{age}" }
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.