Challenge - 5 Problems
Array and Set Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using array intersection?
Consider the following Ruby code snippet. What will it print?
Ruby
a = [1, 2, 3, 4] b = [3, 4, 5, 6] puts (a & b).inspect
Attempts:
2 left
💡 Hint
The & operator returns elements common to both arrays.
✗ Incorrect
The & operator in Ruby returns a new array containing elements common to both arrays, without duplicates. Here, 3 and 4 are common.
❓ Predict Output
intermediate2:00remaining
What does this Ruby code print when using array difference?
Look at this Ruby code. What is the output?
Ruby
a = [1, 2, 3, 4] b = [3, 4, 5, 6] puts (a - b).inspect
Attempts:
2 left
💡 Hint
The - operator removes elements from the first array that appear in the second.
✗ Incorrect
The - operator returns a new array with elements from the first array that are not in the second. So 3 and 4 are removed from a.
❓ Predict Output
advanced2:00remaining
What is the output of this Ruby code using array union?
What will this Ruby code print?
Ruby
a = [1, 2, 3] b = [3, 4, 5] puts (a | b).inspect
Attempts:
2 left
💡 Hint
The | operator returns all unique elements from both arrays.
✗ Incorrect
The | operator returns a new array with unique elements from both arrays combined. Duplicates are removed.
❓ Predict Output
advanced2:00remaining
What error does this Ruby code raise when comparing arrays with a non-array?
What error will this Ruby code produce?
Ruby
a = [1, 2, 3] b = 5 puts (b & a).inspect
Attempts:
2 left
💡 Hint
The & operator expects both operands to be arrays.
✗ Incorrect
The & operator is defined for arrays. Using it with an Integer on the left causes NoMethodError because Integer does not have & method.
🧠 Conceptual
expert3:00remaining
How many unique elements are in the result of this Ruby array operation?
Given the arrays below, how many elements are in the array resulting from (a | b) - (a & b)?
Ruby
a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7] result = (a | b) - (a & b) puts result.size
Attempts:
2 left
💡 Hint
Think about the symmetric difference: elements in either array but not both.
✗ Incorrect
The expression (a | b) - (a & b) gives the symmetric difference. Here, a | b is [1,2,3,4,5,6,7], a & b is [4,5]. Removing [4,5] leaves [1,2,3,6,7], which has 5 elements.