zip
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: