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

后端 未结 4 1571
南旧
南旧 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:25

    The Problem

    In Ruby, private methods can't be called directly with an explicit receiver; self doesn't get any special treatment here. By definition, when you call self.some_method you are specifying self as the explicit receiver, so Ruby says "No!"

    The Solution

    Ruby has rules for its method lookups. There may be a more canonical source for the rules (other than going to the Ruby source), but this blog post lays out the rules right at the top:

    1) Methods defined in the object’s singleton class (i.e. the object itself)
    2) Modules mixed into the singleton class in reverse order of inclusion
    3) Methods defined by the object’s class
    4) Modules included into the object’s class in reverse order of inclusion
    5) Methods defined by the object’s superclass, i.e. inherited methods
    

    In other words, private methods are first looked up in self without requiring (or allowing) an explicit receiver.

提交回复
热议问题