Why won't Ruby allow me to specify self as a receiver inside a private method?

后端 未结 4 1573
南旧
南旧 2021-01-13 15:40

Ruby as an Object Oriented Language. What that means is whatever message I send, I strictly send it on some object/instance of class.

Example:

 class         


        
4条回答
  •  清歌不尽
    2021-01-13 16:11

    where is the object that I am sending method on

    It's self. Whenenver you don't specify a receiver, the receiver is self.

    The definition of private in Ruby is that private methods can only be called without a receiver, i.e. with an implicit receiver of self. Interestingly, it didn't bother you at all with the puts method which is also a private instance method ;-)

    Note: there's an exception to this rule. Private setters can be called with an explicit receiver, as long as the receiver is self. In fact, they must be called with an explicit receiver, because otherwise there would be an ambiguity with local variable assignments:

    foo = :fortytwo      # local variable
    self.foo = :fortytwo # setter
    

提交回复
热议问题