If `self` is always an implied receiver in Ruby, why does` self.puts` not work?

In Ruby, I understand that self is the intended receiver for any call to the public method. However:

 ~: irb >> puts "foo" foo => nil >> self.puts "foo" NoMethodError: private method `puts' called for main:Object 

What does this explain?

In case of his help:

 >> method(:puts).owner => Kernel 
+6
source share
4 answers

Private methods cannot have a receiver

I think the answer is this: the Ruby method of ensuring the confidentiality of the method is that it does not allow calling private methods with an explicit recipient.

Example:

 class Baker def bake_cake make_batter self.use_oven # will explode: called with explicit receiver 'self' end private def make_batter puts "making batter!" end def use_oven puts "using oven!" end end b = Baker.new b.bake_cake 

Since there cannot be an explicit receiver, you certainly cannot make b.use_oven . This is how confidentiality is ensured.

+8
source

Because the definition of privacy in Ruby: private methods can only be called with an implicit receiver.

In fact, there is an exception to this rule: since foo = bar always creates a local variable, you are allowed to call private setters like self.foo = bar , because otherwise you cannot call them at all (without using reflection).

+4
source

You are correct that self is the intended recipient unless you specify it explicitly. The reason you are not allowed to do self.puts is because you cannot call private methods with an explicit receiver (even if this receiver is self ), and as stated in the error message, puts is a private method.

+3
source

You cannot access private methods in ruby โ€‹โ€‹using the self. syntax self. , or, generally speaking, using any receiver (something in front of . ). This is only possible for protected methods.

+1
source

Source: https://habr.com/ru/post/921208/


All Articles