All original content is created in Ukrainian. Not all content has been translated yet. Some posts may only be available in Ukrainian.Learn more

Visibility control in Ruby (public, private, and protected)

This content has been automatically translated from Ukrainian.
In Ruby, access to methods is controlled by three keywords: public, private, and protected. These keywords are used to control the visibility of methods in a class (encapsulation).

Public (Public Methods)

Regarding public methods, there are a few key points to remember. Methods declared as public can be called by anyone - both inside and outside the class. By default, all methods in a class are public. You can specify that a method is public, but for brevity and simplicity, this is not usually done.
class MyClass
  def public_method_name
    # This method is public by default
  end

  public :public_method_name  # Explicitly declaring it as public, but it's not necessary
end
class MyClass
  def public_method_name
    # This method is public by default
  end
end
Technically, the examples are identical - public_method_name is a public method.Β 

Private (Private Methods)

Methods declared as private can only be called within the class where they are defined. They cannot be called from outside the class, even from an instance of that class.
class MyClass
  private # all methods that follow this line are private

  def private_method_name
    # This method is private
  end
end

Protected (Protected Methods)

Methods declared as protected can only be called within the same class or instances of its subclasses. It is similar to private access, but allows access for subclasses.
class MyClass
  protected # all methods that follow this line are protected

  def protected_method
    # This method is protected
  end
end
Questions about public, private, and protected are quite common in interviews. This information is best absorbed when learned through examples/exercises. For instance:

Exercise to Learn Public, Private, and Protected Methods

Create a class "User":
  • Create a User class with the following properties: name and age.
  • All properties should be private.
Add Methods:
  • Add a greet method that outputs the message: "Hello, how are you?"
  • Add an access_age method that returns the user's age.
Change Access Levels:
  • Make the greet method public.
  • Make the access_age method protected.
Create a subclass "Admin":
  • Create a subclass Admin that inherits from the User class.
Test the Implementation:
  • Create an object of the User class and an object of the Admin class.
  • Call the greet method on the objects of both classes.
  • Try to access the age using the access_age method on the User class object and try the same on the Admin class object.
Record Your Observations:
  • Note which methods you successfully called and which resulted in an error.
  • Determine which methods can be called from outside the class and which cannot.
Optimize the Code (Refactoring)
  • Organize the code
  • Change method names to more understandable ones (access_age -> age)
Here is a skeleton of code that may help you get oriented:
class User
  def initialize(name, age)
    @name = name
    @age = age
  end

  def greet
    puts "Hello, how are you?"
  end

  def access_age
    @age
  end

  private

  def private_method
    puts "This is a private method"
  end

  protected

  def protected_method
    puts "This is a protected method"
  end
end

class Admin < User
  # Admin inherits all properties and methods from User
end

# Creating objects
user = User.new("User", 25)
admin = Admin.new("Admin", 30)

# Calling the public method
user.greet
admin.greet

# Trying to call the protected method
# user.protected_method  # Will result in an error

# Trying to call the private method
# user.private_method  # Will result in an error

# Output age
puts "User's age: #{user.access_age}"
puts "Admin's age: #{admin.access_age}"
If this exercise seems challenging - come back to it after some time. Review how classes work, what initialize is, what an instance of a class is, etc.
Π―ΠΊΡ‰ΠΎ всі ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΈ ΠΌΠ°Ρ‚ΠΈΠΌΡƒΡ‚ΡŒ ΠΌΠΎΠ΄ΠΈΡ„Ρ–ΠΊΠ°Ρ‚ΠΎΡ€ доступу public, Ρ†Π΅ ΠΏΡ€ΠΈΠ·Π²Π΅Π΄Π΅ Π΄ΠΎ Ρ‚ΠΎΠ³ΠΎ, Ρ‰ΠΎ всі Ρ–Π½ΡˆΡ– класи Ρ‚Π° ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚ΠΈ ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΈ ΠΌΠ°Ρ‚ΠΈΠΌΡƒΡ‚ΡŒ Π±Π΅Π·ΠΏΠ΅Ρ€Π΅ΡˆΠΊΠΎΠ΄Π½ΠΈΠΉ доступ Π΄ΠΎ Ρ†ΠΈΡ… ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ–Π².
Π¦Π΅ ΠΌΠΎΠΆΠ΅ призвСсти Π΄ΠΎ Π½Π΅ΠΏΠ΅Ρ€Π΅Π΄Π±Π°Ρ‡ΡƒΠ²Π°Π½ΠΈΡ… ΠΊΠΎΠ½Ρ„Π»Ρ–ΠΊΡ‚Ρ–Π² Ρƒ ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΡ–.
Π— Ρ–Π½ΡˆΠΎΠ³ΠΎ Π±ΠΎΠΊΡƒ, Ρ†Π΅ ΠΌΠΎΠΆΠ΅ ΠΏΠΎΠ»Π΅Π³ΡˆΠΈΡ‚ΠΈ Π²Π·Π°Ρ”ΠΌΠΎΠ΄Ρ–ΡŽ ΠΌΡ–ΠΆ класами Ρ‚Π° сприяти ΡˆΠ²ΠΈΠ΄ΠΊΠΎΡ— Ρ€ΠΎΠ·Ρ€ΠΎΠ±Ρ†Ρ–, Π°Π»Π΅ Ρ‚Π°ΠΊΠΈΠΉ ΠΏΡ–Π΄Ρ…Ρ–Π΄ Π½Π΅ Π·Π°Π²ΠΆΠ΄ΠΈ Ρ” Π±Π΅Π·ΠΏΠ΅Ρ‡Π½ΠΈΠΌ Ρ– ΠΌΠΎΠΆΠ΅ ΠΏΠΎΡ€ΠΎΠ΄ΠΆΡƒΠ²Π°Ρ‚ΠΈ ΠΏΡ€ΠΎΠ±Π»Π΅ΠΌΠΈ Π·Ρ– збСрСТСнням Π΄Π°Π½ΠΈΡ… Ρ‚Π° ΠΊΠΎΠ½Ρ„Ρ–Π΄Π΅Π½Ρ†Ρ–ΠΉΠ½Ρ–ΡΡ‚ΡŽ.
24 Jul 11:47

How to change the language in Steam to Ukrainian?

meme code
meme code@memecode
24 Jul 12:01

What is "Vulkan Shader Processing" in Steam?

meme code
meme code@memecode
24 Jul 12:17

How to make Counter-Strike: GO fullscreen in Ubuntu without launching the game?

meme code
meme code@memecode
20 Nov 19:35

How to recover a deleted file (Trix) that was stored on Amazon S3?

meme code
meme code@memecode
29 Nov 08:47

What is the difference between var and let in Javascript?

meme code
meme code@memecode
07 Dec 07:42

What is encapsulation in OOP?

meme code
meme code@memecode
07 Dec 08:25

What is OOP (object-oriented programming)?

meme code
meme code@memecode
09 Dec 12:00

What is inheritance in Ruby? Examples of bad and good inheritance.

meme code
meme code@memecode
09 Dec 12:15

What is best practice in programming?

meme code
meme code@memecode
09 Dec 12:21

What is polymorphism? An example of using polymorphism in Ruby.

meme code
meme code@memecode
09 Dec 12:46

Π©ΠΎ Ρ‚Π°ΠΊΠ΅ ΠΏΠ°Ρ‚Π΅Ρ€Π½/шаблон проєктування?

meme code
meme code@memecode
10 Dec 14:03

What is a design pattern in programming?

meme code
meme code@memecode