Search code examples
rubyselfprivate-members

Ruby: calling private methods from inside with 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 results in an output:

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 calling methods from inside with self keyword and without it?

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


Solution

  • In ruby a private method is simply one that cannot be called with an explicit receiver, i.e with anything to the left of the ., no exception is made for self, except in the case of setter methods (methods whose name ends in =)

    To disambiguate a non setter method call you can also use parens, ie

    my_id()
    

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

    def my_id=(val)
    end
    

    then you can't make ruby parse this as a method call by adding parens. You have to use self.my_id= for ruby to parse this as a method call - this is the exception to "you can't call setter methods with an explicit receiver"