Read private method - Ruby

Asked

Viewed 132 times

1

Hello, everybody.

class Automovel

  def self.tipo_cambio
    puts "Manual"
  end

  def acelera
    verifica_combustivel()
    # Injetando combustível
    puts "Acelerando automóvel"
    freia()
  end

  private
    def verifica_combustivel
      puts "verificando combustível!!!"
    end
end

#-----------

class Carro < Automovel

  def freia
    puts "freiando"
    #acelera()
    verifica_combustivel()
  end
end

I’ve been studying Ruby, and in making this code I came across a question.

When creating an instance of the Automovel class in the terminal (alias car = Car.new) he usually reads the method accelerates of Automovel giving the command car. (returns "injecting fuel" etc.), but when calling the brake method of the Car class by car.freia, it returns the check method. I want to understand why it returns normally if the method is private and can be accessed only by the Automovel class?

3 answers

0

Renan, I understand that any car type object has access to the private method that has been set, since Car is inheriting from the Car class.

You can better understand the concept by reading here in doc

0

Access modifiers vary from language to language. In Ruby, private methods can be accessed by child classes.

0

You can call a private method within a subclass because you put it within a public method.

The same logic applies to attr_accessor which is nothing more than a macro for two writing and reading methods.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.