Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 44 / 68

Pairing Up Two Arrays (the zip operation)

In this lesson you will learn to pair up two arrays with Ruby's zip method. This is for anyone searching for "Ruby zip how to use".

Combining two corresponding arrays - a list of names and a list of scores, say - into pairs one by one is called a zip operation. Picture matching socks into left-and-right pairs. Ruby has a method named exactly that: .zip.

The sample code builds an array of name-and-score pairs with nothing more than names.zip(scores). Notice how .inspect shows the contents of the array readably.

A common stumbling block for beginners is how to combine three or more arrays. You simply add them to zip: a.zip(b, c) extends by adding arguments, which is a pleasantly flexible design.

It is also a frequent choice when you want to loop over several arrays at once - useful whenever you want to turn separately managed data into a single combined object for display.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)