0
0
Rubyprogramming~5 mins

Subclass with < operator in Ruby

Choose your learning style9 modes available
Introduction
The < operator helps you check if one class is a child (subclass) of another class. It shows if one class inherits from another.
When you want to see if a class is based on another class.
When you need to organize classes in a family tree and check relationships.
When you want to run code only if a class is a subclass of another.
When debugging to understand class inheritance.
When designing flexible code that works differently for subclasses.
Syntax
Ruby
ChildClass < ParentClass
Returns true if ChildClass inherits from ParentClass.
Returns nil if there is no inheritance relationship.
Examples
Dog is a subclass of Animal, so Dog < Animal is true. Animal is not a subclass of Dog, so Animal < Dog is nil.
Ruby
class Animal; end
class Dog < Animal; end

puts Dog < Animal  # true
puts Animal < Dog  # nil
Car inherits from Vehicle, so Car < Vehicle is true. Bike does not inherit from Vehicle, so Bike < Vehicle is nil.
Ruby
class Vehicle; end
class Car < Vehicle; end
class Bike; end

puts Car < Vehicle  # true
puts Bike < Vehicle # nil
Sample Program
This program checks if Apple and Orange are subclasses of Fruit, and if Car is a subclass of Fruit.
Ruby
class Fruit; end
class Apple < Fruit; end
class Orange < Fruit; end
class Car; end

puts Apple < Fruit
puts Orange < Fruit
puts Car < Fruit
OutputSuccess
Important Notes
The < operator works only with classes and modules in Ruby.
If you use it with unrelated classes, it returns nil.
It helps understand inheritance without creating objects.
Summary
The < operator checks if one class inherits from another.
It returns true for subclasses and nil otherwise.
Use it to understand or control class relationships.