I'm learning Ruby, and have come up to a point where I am confused.
The book I am using is talking about private
, public
, and protected methods
, but I am still a bit confused. What are the differences between each?
Differences. First and important difference is the accessibility i.e. anything public is accessible to anywhere , anything private is only accessible in the class they are declared , anything protected is accessible outside the package but only to child classes and default is accessible only inside the package.
As you have seen the difference between private and public lies in how accessible a particular field, method, or class would have. public means you can access it anywhere while private means you can only access it inside its own class.
The difference between public and protected is that public can be accessed from outside class but protected cannot be accessed from outside class. In the example above, we created a protected method inside the Addition class. Later, we extended the Test class to use the Addition class.
Things that are private are only visible within the class itself. Things that are protected are visible in the class itself and in subclasses.
Public - can be called from anywhere
Private - The method cannot be called outside class scope. The object can only send the message to itself
ex: the baker has bake
method as public but break_eggs
is private
Protected - You can call an object's protected methods as long as the default object self
is an instance of the same class as the object whose method you're calling
ex: with n
protected method, c1
can ask c2
to execute c2.n
, because c1
and c2
are both instances of the same class
And last but not least:
if "class D < C", then D will exhibit the same access behaviour as instances of C
reference: http://www.amazon.com/Ruby-Rails-Techniques-Developers/dp/1932394699
public
methods are open to everyone. As for private
versus protected
, I refer to "Ruby Private Methods vs. Protected Methods":
What is the difference between 'private' and 'protected' methods in Ruby? In Ruby, the primary difference between a 'private' and 'protected' method is that a private method cannot be called with an explicit receiver, while a protected method can. What is an 'explicit receiver', you ask? An explicit receiver is the object that is receiving a message. In the following example, we have a receiver ('parent') and a method ('get_name'). The 'parent' object is receiving the instruction to perform the 'get_name' method.
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