Recall & Review
beginner
What does the
prepend method do in Ruby?It inserts a module before the current class in the method lookup chain, so methods in the prepended module override the class's own methods.Click to reveal answer
intermediate
How is
prepend different from include in Ruby?<code>include</code> adds a module after the class in the method lookup chain, so class methods override module methods. <code>prepend</code> adds the module before the class, so module methods override class methods.Click to reveal answer
intermediate
Why use
prepend for method chain insertion?Because it lets you insert behavior before existing methods without changing the original class, enabling method wrapping or overriding cleanly.
Click to reveal answer
beginner
Given this code:<br><pre>module M
def greet
"Hello from M"
end
end
class C
def greet
"Hello from C"
end
end
c = C.new
puts c.greet</pre><br>What will <code>c.greet</code> print after <code>C.prepend(M)</code>?It will print "Hello from M" because
prepend puts module M before class C in the method lookup chain.Click to reveal answer
intermediate
How can you call the original method from a prepended module's method?
Use <code>super</code> inside the prepended module's method to call the original method defined in the class or other modules further down the chain.Click to reveal answer
What happens when you use
prepend with a module in Ruby?✗ Incorrect
prepend inserts the module before the class in the method lookup chain, so the module's methods override the class's methods.
Which keyword lets you call the original method from inside a prepended module's method?
✗ Incorrect
super calls the next method in the lookup chain, allowing access to the original method.
If a module is included instead of prepended, which methods take precedence?
✗ Incorrect
include adds the module after the class, so class methods override module methods.
Why might you use
prepend instead of reopening a class to override a method?✗ Incorrect
prepend allows inserting behavior cleanly without modifying the original class code.
What will this code output?<br>
module M
def hello
"Hi from M" + super
end
end
class C
def hello
"Hi from C"
end
end
C.prepend(M)
puts C.new.hello✗ Incorrect
The prepended module's hello calls super, which calls the class's hello, so the output concatenates both strings.
Explain how
prepend changes the method lookup chain in Ruby and why that is useful for method chain insertion.Think about where the module sits compared to the class in the search for methods.
You got /4 concepts.
Describe how you can use
super inside a prepended module's method to extend behavior rather than replace it.How do you keep the original method's effect while adding new behavior?
You got /4 concepts.