Bird
0
0

Which of the following is the correct way to define a method_added hook inside a Ruby class?

easy📝 Syntax Q12 of 15
Ruby - Advanced Metaprogramming
Which of the following is the correct way to define a method_added hook inside a Ruby class?
Adef self.method_added(method_name); puts "Added: #{method_name}"; end
Bdef self.method_added; puts "Added method"; end
Cdef method_added(method_name); puts "Added: #{method_name}"; end
Ddef method_added; puts "Added method"; end
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct method signature

    The method_added hook is an instance method of the class's singleton class, so it should be defined as an instance method inside the class (not a class method). It receives the method name as a symbol.
  2. Step 2: Check the options

    def method_added(method_name); puts "Added: #{method_name}"; end defines def method_added(method_name) which is correct. def self.method_added(method_name); puts "Added: #{method_name}"; end defines it as a class method (self.method_added), which is incorrect. Options B and C miss the required parameter.
  3. Final Answer:

    def method_added(method_name); puts "Added: #{method_name}"; end -> Option C
  4. Quick Check:

    method_added is an instance method with one parameter [OK]
Quick Trick: Define method_added as instance method with one parameter [OK]
Common Mistakes:
  • Defining method_added as a class method
  • Omitting the method_name parameter
  • Using wrong method signature without parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes