Bird
0
0

Identify the error in this Ruby class using Enumerable:

medium📝 Debug Q14 of 15
Ruby - Enumerable and Collection Processing
Identify the error in this Ruby class using Enumerable:
class MyList
  include Enumerable
  def initialize(items)
    @items = items
  end
  def each
    @items.each
  end
end

list = MyList.new([1, 2, 3])
p list.select { |x| x > 1 }
AThe initialize method is missing.
BThe each method does not yield elements to the block.
Cselect method is not defined in Enumerable.
DEnumerable cannot be included in custom classes.
Step-by-Step Solution
Solution:
  1. Step 1: Check the each method implementation

    The each method calls @items.each but does not yield elements to the block given to MyList's each.
  2. Step 2: Understand why this causes an error

    Enumerable methods expect each to yield elements; without yield, methods like select won't work properly.
  3. Final Answer:

    The each method does not yield elements to the block. -> Option B
  4. Quick Check:

    each must yield elements = D [OK]
Quick Trick: Ensure each yields elements to the block [OK]
Common Mistakes:
  • Assuming calling each without yield is enough
  • Thinking Enumerable can't be included
  • Believing select is not part of Enumerable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes