Consider the following Ruby code that uses zip to combine arrays. What will it print?
a = [1, 2, 3] b = ['a', 'b', 'c'] result = a.zip(b) puts result.inspect
Remember that zip pairs elements by their index from each array.
The zip method pairs elements from each array by their index. Since both arrays have 3 elements, the result is an array of 3 pairs.
Look at this Ruby code where arrays of different lengths are zipped. What is the output?
x = [10, 20] y = ['x', 'y', 'z'] result = x.zip(y) puts result.inspect
The length of the resulting array matches the receiver array's length.
The zip method returns an array with the same length as the first array. Extra elements in the second array are ignored.
Examine this Ruby code snippet. It raises an error. What is the cause?
a = [1, 2, 3] b = nil result = a.zip(b) puts result.inspect
Think about what zip does internally with its arguments.
The zip method tries to convert arguments to arrays using to_ary. Since nil does not have this method, it raises NoMethodError.
What is the output of this Ruby code that uses zip with a block?
a = [1, 2, 3] b = ['x', 'y', 'z'] a.zip(b) { |num, char| puts "#{num}-#{char}" }
Remember what zip returns when given a block.
When zip is called with a block, it yields each combined array to the block and returns nil.
Given these arrays, how many pairs will the zipped array contain?
arr1 = [5, 10, 15, 20] arr2 = ['a', 'b'] arr3 = [:x, :y, :z] result = arr1.zip(arr2, arr3)
The number of pairs equals the length of the first array.
The zip method returns an array with the same length as the first array, pairing elements from all given arrays by index.