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.
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.
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.
Basically, following the Object Oriented paradigm you can always call a private or protected method within the own class.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With