RubyGuides
Share this post!

Array#zip Method

Let’s say that you want to compare two arrays, element by element so you can find the differences.

Or maybe you want to find the biggest number on every index, or you just want to merge a list of keys & a list of values to build a hash…

…the “hard way” to do this would look something like this.

Example:

That gets the job done, but it’s not very pretty, right?

In addition, you also have to stop & think for a minute to understand what’s going on.

Here’s is where Array#zip (also Enumerable#zip) comes into play!

Example:

Aha! …much better.

Do you agree?

If we are familiar with zip we will instantly understand what’s going on. And if we don’t, a quick read of the documentation (or even better, this article!) will explain it.

Another advantage of using zip is that we can easily chain it with other Enumerable methods.

Like for example, the count method:

This code returns a count of exactly how many elements are the same & in the same position.

Another trick you can use, like I mentioned before, is to merge a list of keys & values to build a hash.

Example:

Want another example?

Ok!

Here it is:

This is a fancy implementation of the caesar cipher algorithm.

Summary

You learned about the Array#zip method, which allows you to “merge” two arrays & do some cool tricks with that 🙂

If you enjoyed this post don’t forget to share it on your favorite social network so more people can read it!

Leave a Comment:

7 comments
Yunlei says last month

great article!

in the coding example of caesar cipher, I think you have an unused shift var 🙂
maybe translation_map = letters.zip(letters.rotate(shift)).to_h ?

Reply
    Jesus Castello says last month

    Thank you! I fixed that 🙂

    Reply
Mr. Ahmed says last month

Very nice article Castello
Thank you 🙂

Reply
Cecilia says last month

Great article!
I always learn so much with you!

Reply
    Jesus Castello says last month

    Thanks for reading & leaving a nice comment Cecilia 🙂

    Reply
Tom Connolly says a couple of weeks ago

Thanks for these bits of wisdom!

Reply
    Jesus Castello says a couple of weeks ago

    Thanks for reading! 🙂

    Reply
Add Your Reply