0
0
Rubyprogramming~10 mins

Subclass with < operator in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Subclass with < operator
Define Parent Class
Define Subclass < Parent
Override < operator method
Create Subclass Instances
Compare Instances with <
Return true/false based on logic
This flow shows how to create a subclass that overrides the < operator to compare instances based on custom logic.
Execution Sample
Ruby
class Animal
  attr_reader :age
  def initialize(age)
    @age = age
  end
end

class Dog < Animal
  def <(other)
    age < other.age
  end
end

puts Dog.new(3) < Dog.new(5)
This code defines a subclass Dog that inherits from Animal and overrides the < operator to compare dogs by age.
Execution Table
StepActionEvaluationResult
1Create Dog instance with age 3Dog.new(3)Dog object with age=3
2Create Dog instance with age 5Dog.new(5)Dog object with age=5
3Compare Dog(3) < Dog(5)3 < 5true
4Print resultputs truetrue printed to console
5End of programNo more codeProgram stops
💡 Program ends after printing the comparison result.
Variable Tracker
VariableStartAfter 1After 2Final
dog1.agenil333
dog2.agenilnil55
comparison_resultnilniltruetrue
Key Moments - 2 Insights
Why do we override the < method in the subclass?
We override < in the subclass to define how two subclass objects should be compared, as shown in execution_table row 3 where Dog(3) < Dog(5) uses the custom logic.
What does the < operator compare inside the method?
Inside the < method, it compares the age attributes of the two Dog instances, as seen in execution_table row 3 where 3 < 5 is evaluated.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of Dog.new(3) < Dog.new(5)?
Anil
Bfalse
Ctrue
DError
💡 Hint
Check execution_table row 3 where the comparison 3 < 5 evaluates to true.
At which step is the Dog instance with age 5 created?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 2 where Dog.new(5) is created.
If we change dog1's age to 6, what would Dog.new(6) < Dog.new(5) return?
Afalse
Btrue
Cnil
DError
💡 Hint
Refer to variable_tracker and execution_table row 3 logic: 6 < 5 is false.
Concept Snapshot
Subclass with < operator in Ruby:
- Define subclass with < ParentClass
- Override < method to compare attributes
- Use instance variables for comparison
- Return true/false based on logic
- Enables custom object comparisons
Full Transcript
This example shows how to create a subclass in Ruby that overrides the less-than operator (<). We define a parent class Animal with an age attribute. Then we create a subclass Dog that inherits from Animal. Inside Dog, we override the < method to compare the age of two Dog instances. When we create two Dog objects with ages 3 and 5, comparing them with < calls our custom method, which returns true because 3 is less than 5. The program prints true and then ends.