Bird
0
0

Given this Ruby class, what will obj.respond_to?(:handle_event) return?

hard📝 Application Q8 of 15
Ruby - Metaprogramming Fundamentals

Given this Ruby class, what will obj.respond_to?(:handle_event) return?

class EventHandler
  def respond_to_missing?(method_name, include_private = false)
    method_name.to_s.end_with?("_event")
  end

  def method_missing(method_name, *args)
    "Handled #{method_name}" if respond_to_missing?(method_name)
  end
end

obj = EventHandler.new
Atrue
Bfalse
Cnil
DRaises NoMethodError
Step-by-Step Solution
Solution:
  1. Step 1: Analyze respond_to_missing?

    It returns true only if method_name ends with "_event".
  2. Step 2: Check method name

    Method name is :handle_event, which ends with "_event" so respond_to_missing? returns true.
  3. Step 3: Understand respond_to?

    However, respond_to? calls respond_to_missing? with include_private default false, so it should return true.
  4. Step 4: Re-examine code

    But the question asks what obj.respond_to?(:handle_event) returns. Since respond_to_missing? returns true, answer should be true.
  5. Final Answer:

    true -> Option A
  6. Quick Check:

    Does method end with '_event'? Yes. [OK]
Quick Trick: respond_to? uses respond_to_missing? to check method presence [OK]
Common Mistakes:
  • Ignoring method name pattern
  • Confusing respond_to? return values
  • Assuming method_missing affects respond_to?

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes