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.


a = [1,2,3,4,5]
b = [1,2,3,6,8]

c = { |_, idx| [a[idx], b[idx]] }

# [[1, 1], [2, 2], [3, 3], [4, 6], [5, 8]]

That gets the job done, but it’s not 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!


a = [1,2,3,4,5]
b = [1,2,3,6,8]

c =

# [[1, 1], [2, 2], [3, 3], [4, 6], [5, 8]]

Aha! …much better.

Don’t 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:

a = [1,2,3,4,5]
b = [1,2,3,6,8]

c = { |a,b| a == b }

# 3

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

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


a = %w(bacon coconut walnuts)
b = [100, 200, 300]

# {"bacon"=>100, "coconut"=>200, "walnuts"=>300}

Want another example?


Here it is:

letters = Array('a'..'z')
shift   = 3

translation_map =

"hello" { |ch| translation_map[ch] }.join

This is a fancy implementation of the caesar cipher algorithm.


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!

Yunlei says 5 years ago

great article!

in the coding example of caesar cipher, I think you have an unused shift var 🙂
maybe `translation_map =` ?

    Jesus Castello says 5 years ago

    Thank you! I fixed that 🙂

Mr. Ahmed says 5 years ago

Very nice article Castello
Thank you 🙂

Cecilia says 5 years ago

Great article!
I always learn so much with you!

    Jesus Castello says 5 years ago

    Thanks for reading & leaving a nice comment Cecilia 🙂

Tom Connolly says 5 years ago

Thanks for these bits of wisdom!

    Jesus Castello says 5 years ago

    Thanks for reading! 🙂

Comments are closed