Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 16 of 23 · Ruby 3.2

Specialize a class with inheritance

Reuse a superclass and extend a method with super.

Learn

A subclass inherits methods from its superclass. class UrgentNotice < Notice makes UrgentNotice a subclass of Notice. The subclass can use the inherited initialize method and define its own label method.

An overriding method replaces the inherited implementation for that call. Inside the override, super invokes the next implementation of the same method in the ancestor chain. Here that is Notice#label. With no parentheses, super forwards the arguments the current method received; super(text) passes text explicitly, while super() passes no arguments.

Example

class Notice
  def initialize(text)
    @text = text
  end
  def label
    @text
  end
end
class UrgentNotice < Notice
  def label
    "Urgent: #{super}"
  end
end
puts Notice.new("Delivery today").label
puts UrgentNotice.new("Delivery today").label

Experiment

  • Predict which label method runs for each object. Change the subclass prefix, then check whether the superclass output changes.

  • Predict the label. Change the priority argument and then the text argument; trace which initializer stores each value.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.