Private Methods
Learn why and how to make methods private.
We'll cover the following
Remember that instance variables store data private to the object. Instance variables are only made accessible to the outside world (exposed) if we add attribute accessors to the class.
In the same way, classes sometimes want to keep certain methods private. These are methods that aren’t supposed to be called from outside of the object. Only the object itself is supposed to use them internally by calling them from its own other methods.
Imagine an instance of an ItalianRestaurant
class with a pizza
method, which is supposed to return an instance of the Pizza
class.
When we call the pizza
method (ask for a pizza), it should know what to do and how to do it. Dough will be prepared, sauce and vegetables and other such things will be gathered, and the pizza will be baked and served.
We don’t really care about these details, though. We’re hungry and just want a pizza. The exact steps involved are kept private, and perhaps they’ve been the family’s best-kept secret for generations.
This is essentially how objects work too! The ItalianRestaurant
object exposes some stuff to the outer world (us) and keeps other things private. They’ll let us order a pizza and other things. But they won’t tell us the exact ingredients of their tomato sauce, or how they managed to make this great pizza dough.
Making a method private
In our Person
example, it makes sense to make the encrypt
method private.
Currently, if we run the following code, it executes just fine, even though it makes little sense:
person = Person.new("Ada")p person.encrypt("some other secret")
Why would a person encrypt some arbitrary string for someone else and return it? This is something that the Person
object should keep private. The restaurant wouldn’t turn flour, water, olive oil, and other ingredients into pizza dough for everyone else either.
Making encrypt private
We can make the encrypt
method private like this:
module Encryptionprivatedef encrypt(string)Digest::SHA2.hexdigest(string)endend
Remember: The
private
keyword tells Ruby that all methods defined from now on are supposed to be private. They can be called from within the object (from other methods the class defines) but not from outside.
If we try to call the method now, it raises an error:
person = Person.new("Ada")p person.encrypt("super secret")
This prints the error message:
private method `encrypt' called for #<Person:0x007fa179863770 @name="Ada">