Challenge - 5 Problems
Enumerable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Enumerable#map with a block
What is the output of this Ruby code using Enumerable's map method?
Ruby
numbers = [1, 2, 3, 4] result = numbers.map { |n| n * 2 } puts result.inspect
Attempts:
2 left
💡 Hint
Enumerable#map applies the block to each element and returns a new array.
✗ Incorrect
The map method takes each element, multiplies it by 2, and returns a new array with these values.
🧠 Conceptual
intermediate1:30remaining
Why does Enumerable require #each?
Why does the Enumerable module require the including class to define the #each method?
Attempts:
2 left
💡 Hint
Enumerable methods rely on a way to visit each element in a collection.
✗ Incorrect
Enumerable uses the #each method to loop through elements, so it must be defined by the class.
🔧 Debug
advanced2:30remaining
Fix the error when using Enumerable methods
What error will this code produce and why?
class Box
include Enumerable
def initialize(items)
@items = items
end
end
box = Box.new([1, 2, 3])
box.map { |x| x * 2 }
Attempts:
2 left
💡 Hint
Enumerable needs #each to work properly.
✗ Incorrect
The Box class includes Enumerable but does not define #each, so calling map raises NoMethodError.
🚀 Application
advanced3:00remaining
Implement #each to use Enumerable methods
Complete the Box class so that Enumerable methods like #select work correctly on its items.
Ruby
class Box include Enumerable def initialize(items) @items = items end # Your code here end box = Box.new([1, 2, 3, 4]) selected = box.select { |x| x.even? } puts selected.inspect
Attempts:
2 left
💡 Hint
The #each method must yield each element to the block.
✗ Incorrect
Defining #each to yield each item allows Enumerable methods to iterate properly.
❓ Predict Output
expert2:00remaining
Output of Enumerable#reduce with initial value
What is the output of this Ruby code using Enumerable's reduce method with an initial value?
Ruby
values = [2, 3, 4] result = values.reduce(10) { |sum, n| sum + n } puts result
Attempts:
2 left
💡 Hint
Reduce starts with the initial value and adds each element.
✗ Incorrect
Starting from 10, adding 2, then 3, then 4 results in 19.