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:
a = [1,2,3,4,5] b = [1,2,3,6,8] c = a.map.with_index { |_, 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!
Example:
a = [1,2,3,4,5] b = [1,2,3,6,8] c = a.zip(b) # [[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.zip(b).count { |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.
Example:
a = %w(bacon coconut walnuts) b = [100, 200, 300] a.zip(b).to_h # {"bacon"=>100, "coconut"=>200, "walnuts"=>300}
Want another example?
Ok!
Here it is:
letters = Array('a'..'z') shift = 3 translation_map = letters.zip(letters.rotate(shift)).to_h "hello".chars.map { |ch| translation_map[ch] }.join
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!
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` ?
Thank you! I fixed that 🙂
Very nice article Castello
Thank you 🙂
Great article!
I always learn so much with you!
Thanks for reading & leaving a nice comment Cecilia 🙂
Thanks for these bits of wisdom!
Thanks for reading! 🙂