Using Zip in Ruby

Last week I blogged about the Enumerable module in Ruby and specifically mentioned the Enumerable#zip method. I didn’t think the zip method was particularly useful, but I have actually found a few extra features which are very nice.

To refresh your memory, the zip method will combine the elements of two different arrays.

names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }

p names.zip(surnames)
# [["Michael", "Bluth"], ["Tobias", "Funke"], ["Ann", "Veal"], ["Barry","Zuckerkorn"]]

I also mentioned that you can actually combine multiple arrays in this way.

names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }
ages = [ 42, 44, 17, 49 ]

p names.zip(surnames, ages)
# [["Michael", "Bluth", 42], ["Tobias", "Funke", 44], ["Ann", "Veal", 17], ["Barry","Zuckerkorn", 49]]

What I didn’t realize was that you can very easily create a hash mapping between two arrays when you use this method in combination with the [] method on the Hash class.

names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }

p Hash[names.zip(surnames)]
# {"Tobias"=>"Funke", "Michael"=>"Bluth", "Ann"=>"Veal", "Barry"=>"Zuckerkorn"}

This is a pretty cool trick. Lastly, we can actually pass a block to the zip method – the block will execute exactly the same as an each block executed on the result.

names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }
ages = [ 42, 44, 17, 49 ]

names.zip(surnames, ages) do |elem|
  p elem
end
# ["Michael", "Bluth", 42]
# ["Tobias", "Funke", 44]
# ["Ann", "Veal", 17]
# ["Barry", "Zuckerkorn", 49]

I still don’t really get the name of the method, but it’s pretty useful. Happy coding.