Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
class MyCollection
  include Enumerable
  def initialize(items)
    @items = items
  end
  def each
    @items.each { |item| yield item }
  end
end

col = MyCollection.new([1, 2, 3])
p col.map { |x| x * 2 }
AError: undefined method `map`
B[1, 2, 3]
C[2, 4, 6]
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand how Enumerable works with each

    The class includes Enumerable and defines each to yield items from @items. Calling map on col applies the block multiplying each element by 2, resulting in [2, 4, 6].
  2. Final Answer:

    [2, 4, 6] -> Option C
  3. Quick Check:

    Enumerable map doubles elements [OK]
Quick Trick: Enumerable methods need an each method defined [OK]
Common Mistakes:
  • Forgetting to define each
  • Expecting map without each
  • Confusing map output with original array

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes