Challenge - 5 Problems
Map 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 map?
Consider the following Ruby code that uses
map to transform an array of numbers. What will be printed?Ruby
numbers = [1, 2, 3, 4] result = numbers.map { |n| n * 3 } puts result.inspect
Attempts:
2 left
💡 Hint
Remember,
map creates a new array by applying the block to each element.✗ Incorrect
The map method applies the block { |n| n * 3 } to each element, multiplying each number by 3. So the output is [3, 6, 9, 12].
❓ Predict Output
intermediate2:00remaining
What does this code output when using collect with a condition?
Look at this Ruby code using
collect with a conditional inside the block. What is the output?Ruby
arr = [5, 10, 15, 20] result = arr.collect { |x| x > 10 ? x / 5 : x } puts result.inspect
Attempts:
2 left
💡 Hint
Check how the ternary operator changes values greater than 10.
✗ Incorrect
The block checks if each element is greater than 10. If yes, it divides by 5; otherwise, it keeps the original value. So 15 becomes 3, 20 becomes 4, others stay the same.
🔧 Debug
advanced2:00remaining
Why does this map code raise an error?
This Ruby code tries to use
map to transform an array but raises an error. What is the cause?Ruby
arr = [1, 2, 3] result = arr.map do |x| x * 2 end result = result + 1 puts result.inspect
Attempts:
2 left
💡 Hint
Look at the line where
result is added to 1.✗ Incorrect
The map returns an array, but result + 1 tries to add an integer to an array, causing a TypeError.
❓ Predict Output
advanced2:00remaining
What is the output of this nested map transformation?
Given this Ruby code with nested arrays and
map, what will be printed?Ruby
matrix = [[1, 2], [3, 4]] result = matrix.map { |row| row.map { |n| n + 1 } } puts result.inspect
Attempts:
2 left
💡 Hint
Each inner array is transformed by adding 1 to each element.
✗ Incorrect
The outer map goes through each row (array), and the inner map adds 1 to each number. So each number increases by 1.
🧠 Conceptual
expert2:00remaining
How many elements are in the resulting array after this map?
What is the number of elements in the array returned by this Ruby code?
Ruby
arr = [1, 2, 3, 4, 5] result = arr.map { |x| x if x.even? } puts result.compact.size
Attempts:
2 left
💡 Hint
Remember that
map keeps the same number of elements, but some may be nil.✗ Incorrect
The map returns an array with elements that are even numbers or nil for odd numbers. After compact, only even numbers remain. There are 2 even numbers (2 and 4), so size is 2.
However, the code prints result.compact.size, which is 2.