0
0
Rubyprogramming~20 mins

Map/collect for transformation in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Map Mastery
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 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
A[3, 6, 9, 12]
B[1, 2, 3, 4]
C[1, 4, 9, 16]
Dnil
Attempts:
2 left
💡 Hint
Remember, map creates a new array by applying the block to each element.
Predict Output
intermediate
2: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
A[1, 2, 3, 4]
B[5, 10, 3, 4]
C[5, 10, 15, 20]
D[5, 2, 3, 4]
Attempts:
2 left
💡 Hint
Check how the ternary operator changes values greater than 10.
🔧 Debug
advanced
2: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
ANoMethodError: undefined method `+' for nil:NilClass
BSyntaxError: unexpected end-of-input
CTypeError: no implicit conversion of Integer into Array
DNo error, outputs [3, 4, 5]
Attempts:
2 left
💡 Hint
Look at the line where result is added to 1.
Predict Output
advanced
2: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
A[[2, 3], [4, 5]]
B[[1, 2], [3, 4]]
C[[3, 4], [5, 6]]
D[2, 3, 4, 5]
Attempts:
2 left
💡 Hint
Each inner array is transformed by adding 1 to each element.
🧠 Conceptual
expert
2: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
A3
B0
C5
D2
Attempts:
2 left
💡 Hint
Remember that map keeps the same number of elements, but some may be nil.