When the method is protected, you can call it like a public one, but only if you call it in the context of a class from the same family. Based on my experience, many developers don’t know the difference between private and protected methods, so they won’t use protected when they should. How often do you see protected methods in the source code or define them in your code? I bet not often. As you may also know, all methods are public by default. However, the preferred way of defining access levels is to group methods from the public through private to protected. Sometimes you can see such a solution, so it is good to know how it works. The result is the same, but we use private as an ordinary method. It’s evident that age and location methods are private, but you can also pass arguments to the private method to achieve the same: class Person def name end def age end def location end private :age, :location end Let’s take a look at a very standard example of how we define certain levels of visibility: class Person def name end private def age end def location end end However, I found a few things that are still valuable to learn and may be surprising to you. Public, private, and protected are well known among Ruby developers. It seems that there is nothing more that you can learn about access modifiers in Ruby.
0 Comments
Leave a Reply. |