Ruby: calling private methods from within using the self keyword

class MyClass def test puts my_id puts self.my_id end private def my_id 115 end end m = MyClass.new m.test 

This script outputs the result:

 115 priv.rb:4:in `test': private method `my_id' called for #<MyClass:0x2a50b68> (NoMethodError) from priv.rb:15:in `<main>' 

What is the difference between calls from the inside with the self keyword and without it?

From my experience, Delphi and C #: there was no difference, and self could be used to avoid a name conflict with a local variable, to indicate that I want to call an instance function or refer to an instance variable.

+6
source share
1 answer

In ruby ​​a private method is simply one that cannot be called with an explicit receiver, that is, with anything to the left of . , an exception was not made for self , except when using setter methods (methods whose name ends with = )

To eliminate the ambiguity of calling a non setter method, you can also use parens, i.e.

 my_id() 

For a private setter method, i.e. if you have

 def my_id=(val) end 

then you cannot force ruby ​​to parse this as a method call by adding parens. You must use self.my_id= for ruby ​​to parse this as a method call - this is an exception to "you cannot call setter methods with an explicit receiver"

+2
source

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


All Articles