Arts >> Artes e entretenimento >  >> Magia >> Truques de mágica

Usando `super` em Herança Ruby: Chamando Método Pai

Em Ruby (a linguagem), super é palavra-chave que chama método da classe pai. Não tem nada a ver com item Pokémon "Super Rod" (Super Vara).

Como `super` Funciona

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

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

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

Pontos-Chave

Este é comportamento padrão de herança simples em Ruby.

Truques de mágica

Related Categories