Challenge - 5 Problems
Ruby Method Overriding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of overridden method in subclass
What is the output of the following Ruby code?
Ruby
class Animal def speak "Hello from Animal" end end class Dog < Animal def speak "Woof!" end end puts Dog.new.speak
Attempts:
2 left
💡 Hint
The subclass method with the same name replaces the parent method.
✗ Incorrect
The Dog class overrides the speak method from Animal. So calling speak on Dog instance returns "Woof!".
❓ Predict Output
intermediate2:00remaining
Calling super in overridden method
What will this Ruby code print?
Ruby
class Parent def greet "Hi" end end class Child < Parent def greet super + ", there!" end end puts Child.new.greet
Attempts:
2 left
💡 Hint
super calls the parent method's version.
✗ Incorrect
The Child's greet method calls super to get "Hi" from Parent, then adds ", there!".
❓ Predict Output
advanced2:00remaining
Overriding method with different parameters
What is the output of this Ruby code?
Ruby
class Base def info(x) "Base: #{x}" end end class Derived < Base def info(x, y = nil) if y "Derived: #{x} and #{y}" else super(x) end end end puts Derived.new.info(5) puts Derived.new.info(5, 10)
Attempts:
2 left
💡 Hint
The overridden method uses default parameter and calls super conditionally.
✗ Incorrect
When called with one argument, Derived calls super with that argument, printing "Base: 5". With two arguments, it prints "Derived: 5 and 10".
❓ Predict Output
advanced2:00remaining
Effect of overriding method without calling super
What will this Ruby code output?
Ruby
class Vehicle def description "Vehicle base description" end end class Car < Vehicle def description "Car specific description" end end puts Vehicle.new.description puts Car.new.description
Attempts:
2 left
💡 Hint
Overriding replaces the parent method unless super is called.
✗ Incorrect
Vehicle's description prints its own string. Car overrides description and prints its own string, ignoring Vehicle's.
🧠 Conceptual
expert3:00remaining
Understanding method lookup with overriding and modules
Given this Ruby code, what is the output?
Ruby
module M def greet "Hello from M" end end class A def greet "Hello from A" end end class B < A include M def greet super + " and B" end end puts B.new.greet
Attempts:
2 left
💡 Hint
Modules included in a class come before the superclass in method lookup.
✗ Incorrect
B includes module M, so M's greet is found before A's. B's greet calls super, which calls M's greet, then adds " and B".