0
0
Rubyprogramming~20 mins

Why Enumerable is Ruby's most powerful module - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Enumerable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A[2, 4, 6, 8]
B[1, 2, 3, 4]
C8
Dnil
Attempts:
2 left
💡 Hint
Enumerable#map applies the block to each element and returns a new array.
🧠 Conceptual
intermediate
1:30remaining
Why does Enumerable require #each?
Why does the Enumerable module require the including class to define the #each method?
ABecause Enumerable methods use #each to iterate over elements.
BBecause #each is used to sort elements automatically.
CBecause #each defines the class constructor.
DBecause #each is needed to convert elements to strings.
Attempts:
2 left
💡 Hint
Enumerable methods rely on a way to visit each element in a collection.
🔧 Debug
advanced
2: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 }
ATypeError: can't convert Box to Array
BArgumentError: wrong number of arguments for map
CNoMethodError: undefined method `each' for #<Box:...>
DSyntaxError: unexpected end-of-input
Attempts:
2 left
💡 Hint
Enumerable needs #each to work properly.
🚀 Application
advanced
3: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
A
def each
  yield @items
end
B
def each
  @items.each
end
C
def each
  @items.map { |item| yield item }
end
D
def each
  @items.each { |item| yield item }
end
Attempts:
2 left
💡 Hint
The #each method must yield each element to the block.
Predict Output
expert
2: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
A9
B19
C24
DTypeError
Attempts:
2 left
💡 Hint
Reduce starts with the initial value and adds each element.