Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
Paul Avatar asked Aug 22 '14 13:08

Paul


People also ask

How do you call a private method in Ruby?

Private methods can't be called outside the class. Private methods can be called inside a class inside other methods. Private methods can't be called using an explicit receiver. Private methods are inherited by derived classes.

How do you access private methods in Ruby?

The only way to have external access to a private method is to call it within a public method. Also, private methods can not be called with an explicit receiver, the receiver is always implicitly self. Think of private methods as internal helper methods.

Can an instance call a private method?

Basically, following the Object Oriented paradigm you can always call a private or protected method within the own class.

Can private methods be called by an object?

An object user can use the public methods, but can't directly access private instance variables. You can make methods private too. Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.


1 Answers

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"

like image 104
Frederick Cheung Avatar answered Oct 11 '22 21:10

Frederick Cheung