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.

Paul
  • 25,812
  • 38
  • 124
  • 247
  • possible duplicate of [Understanding private methods in Ruby](http://stackoverflow.com/questions/4293215/understanding-private-methods-in-ruby) – Matt Aug 22 '14 at 13:45

1 Answers1

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"

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • 1
    There is one exception: you can call private setters with an explicit `self` – Stefan Aug 22 '14 at 14:48
  • So you can - hadn't thought to try that out! – Frederick Cheung Aug 22 '14 at 14:50
  • @Stefan, I think "can" should be "must", for the same reason that a public setter must be called with `self`. – Cary Swoveland Aug 22 '14 at 16:38
  • @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. – Jörg W Mittag Aug 22 '14 at 21:11
  • 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. – Frederick Cheung Aug 23 '14 at 02:32