Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 Test
   def test1
    puts "I am in test1. A public method"
    self.test2
   end

   def test2
    puts "I am in test2. A public Method"
   end
 end

makes sense I call method test2 on self object

But I cannot do this

  class Test
   def test1
    puts "I am in test1. A public method"
    self.test2 # Don't work
    test2 # works. (where is the object that I am calling this method on?)
   end

   private
   def test2
    puts "I am in test2. A private Method"
   end
 end

When test2 is public method I can call it on self (fair enough, a method sent to self object). But when test2 is private method I cannot call it on self. So where is the object that I am sending method on?

like image 619
Bhushan Lodha Avatar asked Dec 01 '22 22:12

Bhushan Lodha


1 Answers

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.

like image 63
Todd A. Jacobs Avatar answered Dec 15 '22 22:12

Todd A. Jacobs