0
0
Rubyprogramming~20 mins

Zip for combining arrays in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Zip Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using zip?

Consider the following Ruby code that uses zip to combine arrays. What will it print?

Ruby
a = [1, 2, 3]
b = ['a', 'b', 'c']
result = a.zip(b)
puts result.inspect
A[[1, "a"], [2, "b"]]
B[[1, "a"], [2, "b"], [3, "c"]]
C[[1, "a"], [2, "b"], [3, nil]]
D[[1, 2, 3], ["a", "b", "c"]]
Attempts:
2 left
💡 Hint

Remember that zip pairs elements by their index from each array.

Predict Output
intermediate
2:00remaining
What happens when arrays of different lengths are zipped?

Look at this Ruby code where arrays of different lengths are zipped. What is the output?

Ruby
x = [10, 20]
y = ['x', 'y', 'z']
result = x.zip(y)
puts result.inspect
A[[10, "x"], [20, "y"]]
B[[10, "x"], [20, "y"], [nil, "z"]]
C[[10, "x"], [20, "y"], [20, "z"]]
D[[10, "x"], [20, "y"], [nil, nil]]
Attempts:
2 left
💡 Hint

The length of the resulting array matches the receiver array's length.

🔧 Debug
advanced
2:00remaining
Why does this zip code raise an error?

Examine this Ruby code snippet. It raises an error. What is the cause?

Ruby
a = [1, 2, 3]
b = nil
result = a.zip(b)
puts result.inspect
AArgumentError because <code>zip</code> expects arrays only
BTypeError because <code>nil</code> cannot be converted to array
CNoMethodError because <code>nil</code> does not respond to <code>to_ary</code>
DSyntaxError due to wrong method call
Attempts:
2 left
💡 Hint

Think about what zip does internally with its arguments.

🧠 Conceptual
advanced
2:00remaining
How does zip behave with a block?

What is the output of this Ruby code that uses zip with a block?

Ruby
a = [1, 2, 3]
b = ['x', 'y', 'z']
a.zip(b) { |num, char| puts "#{num}-#{char}" }
A
Prints:
1-x
2-y
3-z
and returns nil
B
Prints:
[1, "x"]
[2, "y"]
[3, "z"]
and returns the zipped array
CPrints nothing and returns the zipped array
D
Prints:
1-x
2-y
3-z
and returns the zipped array
Attempts:
2 left
💡 Hint

Remember what zip returns when given a block.

🚀 Application
expert
2:00remaining
How many pairs are in the zipped array?

Given these arrays, how many pairs will the zipped array contain?

Ruby
arr1 = [5, 10, 15, 20]
arr2 = ['a', 'b']
arr3 = [:x, :y, :z]
result = arr1.zip(arr2, arr3)
A1 pair
B3 pairs
C2 pairs
D4 pairs
Attempts:
2 left
💡 Hint

The number of pairs equals the length of the first array.