Arts >> Kunst en entertainment >  >> Magie >> Goocheltrucs

`super` Gebruiken in Ruby Erfelijkheid: De Ouder-methode Aproepen

In Ruby (de taal) is super een sleutelwoord dat een ouder-klasse's methode aanroept. Het heeft niets te maken met het Pokémon-item "Super Rod."

Hoe `super` Werkt

class Vehicle
  def initialize(brand)
    @brand = brand
  end
  def start
    puts "Starting #{@brand} vehicle..."
  end
end

class Car < Vehicle
  def start
    super # roept Vehicle#start aan
    puts "Engine started. Ready to drive!"
  end
end

Car.new("Toyota").start
# Output:
# Starting Toyota vehicle...
# Engine started. Ready to drive!

Belangrijke Punten

Dit is standaard single-inheritance gedrag in Ruby.

Goocheltrucs

Related Categories