Challenge - 5 Problems
Ruby Subclass Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of subclass comparison with < operator
What is the output of this Ruby code?
Ruby
class Animal def <(other) self.class < other.class end end class Dog < Animal; end class Cat < Animal; end puts Dog.new < Cat.new
Attempts:
2 left
💡 Hint
Remember that Ruby's < operator can be used to compare classes by their inheritance hierarchy.
✗ Incorrect
The < operator compares the classes of the instances using Ruby's built-in Class#< method, which returns true if the left class (self.class) is a subclass of the right class (other.class). Dog is not a subclass of Cat, so it returns false.
❓ Predict Output
intermediate2:00remaining
Subclass comparison with overridden < operator
What does this Ruby code print?
Ruby
class Vehicle def <(other) self.class < other.class end end class Car < Vehicle; end class Truck < Vehicle; end puts Car.new < Truck.new
Attempts:
2 left
💡 Hint
Check if Car is subclass of Truck or vice versa.
✗ Incorrect
The < operator compares the classes. Car is not a subclass of Truck, so Car < Truck returns false.
🔧 Debug
advanced2:00remaining
Why does this subclass < operator code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
class Fruit def <(other) self < other end end class Apple < Fruit; end class Banana < Fruit; end puts Apple.new < Banana.new
Attempts:
2 left
💡 Hint
Look at the < method calling itself.
✗ Incorrect
The < method calls self < other, which calls the same method again, causing infinite recursion and a SystemStackError.
❓ Predict Output
advanced2:00remaining
Output of subclass < operator with modules included
What is the output of this Ruby code?
Ruby
module ComparableModule def <(other) self.class < other.class end end class Parent; include ComparableModule; end class Child < Parent; end class Sibling < Parent; end puts Child.new < Sibling.new
Attempts:
2 left
💡 Hint
Check the inheritance relationship between Child and Sibling.
✗ Incorrect
Child and Sibling are siblings, neither is subclass of the other, so Child < Sibling returns false.
🧠 Conceptual
expert2:00remaining
Understanding < operator behavior in subclass comparison
In Ruby, when you define < operator in a superclass to compare classes of instances using self.class < other.class, what will be the result of comparing an instance of a subclass with an instance of its superclass using < ?
Attempts:
2 left
💡 Hint
Recall how Class#< works in Ruby.
✗ Incorrect
Class#< returns true if the left class is a subclass of the right class. So comparing subclass instance < superclass instance returns true.