How exactly does "private" and "protected" work in Ruby?

Asked

Viewed 92 times

0

I’m studying Ruby and arrived at the access control part. I had studied before access control in Java, then I thought it would be the same, but to my surprise, the statement private and protected are totally different in language Ruby.

My question is, how exactly private and protected work in the Ruby and why the Ruby not accept I call a private method using self ?

class Teste

    def call_private
        self.private_method    # Se eu tirar o "self" ele funciona.
    end

    private

    def private_method
        puts "PRIVADO"
    end
end

teste = Teste.new
teste.call_private

Another thing I just realized, is that if I define my method call_private after the method private_method, Ruby informs me that I’m trying to call a private method.

This means that all method below the statement private are private ? If so, is there any way to create public methods below private methods ?

1 answer

0


The way in which we can perform access control in the Ruby <3 language is theoretically the same as all other languages. However, the syntax is a little different.

All methods, by default, are public, that is, when declaring private_method the Ruby compiler understands that this method will be public.

class Teste

    def call_method
        self.private_method
    end

    def private_method
        "Private"
    end
end

t = Teste.new
puts t.call_method # Retorna Private

Already, if you want it to be private, then yes we should use the reserved word Private before the methods

class Teste

    private

    def call_method
        self.private_method
    end

    def private_method
        "Private"
    end
end

t = Teste.new
puts t.call_method # Nós retorna private method `call_method' called

So all the methods below will be private, that, nor our case, any can be invoked. But, if you wish to return to the public, then we should redeclare them as public in the following way:

class Teste

    # Aqui podemos usar Public ou deixar sem, pois será público por Default
    def call_method
        private_method
    end

    private

    def private_method
        "Private"
    end
end

t = Teste.new
puts t.call_method

Browser other questions tagged

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