0
0
Rubyprogramming~5 mins

Method_added hook in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the method_added hook in Ruby?
It is a special method called automatically whenever a new instance method is added to a class or module.
Click to reveal answer
beginner
How do you define a method_added hook in a Ruby class?
Define a class method named <code>self.method_added(method_name)</code> inside the class or module.
Click to reveal answer
beginner
What argument does the method_added hook receive?
It receives the name of the method (as a symbol) that was just added.
Click to reveal answer
intermediate
Can method_added be used to modify methods after they are defined?
Yes, it can be used to wrap or change methods right after they are added, for example to add logging or validation.
Click to reveal answer
advanced
What happens if you define a method inside method_added itself?
It triggers method_added again, which can cause infinite recursion unless carefully handled.
Click to reveal answer
What does the method_added hook detect in Ruby?
AWhen a new instance method is defined
BWhen a class is created
CWhen a variable is assigned
DWhen a module is included
How do you prevent infinite recursion inside method_added?
ARename the method being added
BAvoid defining methods inside <code>method_added</code>
CCall <code>super</code> inside <code>method_added</code>
DUse a guard variable to skip re-entry
What type of argument does method_added receive?
AMethod body as a string
BMethod name as a symbol
CClass name as a string
DNo arguments
Where should method_added be defined to work properly?
AInside the class or module as a class method
BOutside any class or module
CInside an instance method
DInside a block passed to <code>define_method</code>
Which of these is a common use of method_added?
ACreating new classes
BDeleting methods from a class
CAutomatically wrapping new methods with extra behavior
DChanging variable values
Explain how the method_added hook works and give an example of when you might use it.
Think about how Ruby tells you when a new method appears.
You got /4 concepts.
    Describe a potential problem when defining methods inside method_added and how to avoid it.
    What happens if the hook triggers itself repeatedly?
    You got /4 concepts.