Ruby: calling private methods from inside with self keyword
Asked Answered
P

1

10
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.

Purtenance answered 22/8, 2014 at 13:22 Comment(1)
possible duplicate of Understanding private methods in RubyPhelloderm
S
4

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"

Salerno answered 22/8, 2014 at 13:49 Comment(5)
There is one exception: you can call private setters with an explicit selfAsseveration
So you can - hadn't thought to try that out!Salerno
@Stefan, I think "can" should be "must", for the same reason that a public setter must be called with self.Homorganic
@CarySwoveland is right. It should rather be: you cannot call a private setter without self, because otherwise it would be interpreted as assigning a local variable.Showoff
That was rather poorly worded on my behalf - after Stefan pointed that our I was clumsily trying to say that you can't use parens in this case - presumably that is the motivation for the deviation from the general definition of private.Salerno

© 2022 - 2024 — McMap. All rights reserved.