0
0
Rubyprogramming~20 mins

Subclass with < operator in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Subclass Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
Afalse
BNoMethodError
Ctrue
DArgumentError
Attempts:
2 left
💡 Hint
Remember that Ruby's < operator can be used to compare classes by their inheritance hierarchy.
Predict Output
intermediate
2: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
ANoMethodError
Bfalse
CTypeError
Dtrue
Attempts:
2 left
💡 Hint
Check if Car is subclass of Truck or vice versa.
🔧 Debug
advanced
2: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
ANoMethodError because < is undefined
BArgumentError because of wrong argument type
CSystemStackError due to infinite recursion
DSyntaxError due to missing end
Attempts:
2 left
💡 Hint
Look at the < method calling itself.
Predict Output
advanced
2: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
Atrue
BTypeError
CNoMethodError
Dfalse
Attempts:
2 left
💡 Hint
Check the inheritance relationship between Child and Sibling.
🧠 Conceptual
expert
2: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 < ?
Atrue, because Class#< returns true if left is subclass of right
Bfalse, because subclass is not less than superclass
Ctrue, because subclass is always less than superclass
Dfalse, because Class#< returns true only if left is superclass of right
Attempts:
2 left
💡 Hint
Recall how Class#< works in Ruby.