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

zip

zip pairs up items from two lists like a zipper joining its teeth. The first goes with the first, the second with the second, and so on.

In this page:

  1. zip
Syntax
ruby
array1.zip(array2)

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}" }
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Zipping arrays of different lengths and being surprised by nil, when the shorter array is padded with nil.
  2. Expecting zip to return a hash, when it returns an array of pairs; use .to_h to make a hash.
  3. Zipping the wrong way around, so ages.zip(names) gives [age, name] pairs.
🔒

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.