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:
Syntax
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
names = ["Alice", "Bob", "Cara"]
ages = [30, 25, 40]
paired = names.zip(ages)
puts paired.inspect
paired.each { |name, age| puts "#{name} is #{age}" }
Login to try C/C++/Java/PHP code in the editor
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
- Zipping arrays of different lengths and being surprised by
nil, when the shorter array is padded withnil. - Expecting
zipto return a hash, when it returns an array of pairs; use.to_hto make a hash. - 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: