Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Method Visibility in Ruby
2.1.
Public Visibility
2.2.
Private Visibility
2.3.
Protected Visibility
3.
Frequently Asked Questions
3.1.
What is method visibility?
3.2.
What is the order of method visibility in Ruby?
3.3.
What does the public mean as a modifier?
3.4.
What does private mean as a modifier?
3.5.
What does protected mean as a modifier?
4.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Method Visibility in Ruby

Introduction

Ruby is an object-oriented programming language, which means that it is divided into objects and classes. An object (an instance of a class) is a physical and logical entity in Java. A class, on the other hand, makes perfect sense.

Ruby logo

Each class can have fields, methods, constructors, blocks, nested classes, and interfaces, among other things. It's worth noting that not every class has access to the aforementioned components of another class.

Method Visibility in Ruby defines accessibility, i.e., whether other classes can use a specific field or invoke a specific method in a specific class. In this article, we'll go over the specifics of Ruby's Method Visibility.

Method Visibility in Ruby

In Ruby, we have three levels of Method Visibility based on the extent of an access modifier.

  1. Private: Members of this modifier are private in the sense that they are only visible to their own class.
  2. Public: Members of this modifier are accessible in such a way that they are visible to the entire world.
  3. Protected: Members of this modifier are accessible in such a way that they are visible to their own package and subclasses.
     

In Ruby, the method visibility restrictions are restricted in the following order: public > protected > private.

This order will be discussed in greater detail in the following sections of this article.

Public Visibility

Unless explicitly declared private or protected, methods are usually public. The initialize method is an exception because it is always implicitly private.

Any "global" method declared outside of a class definition is also an exception; these methods are defined as private instance methods of the object. A public method can be called from anywhere; there are no restrictions on how it can be used.

Let’s see an example: 

#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end


   # instance method by default it is public
   def getArea
      getWidth() * getHeight
   end


   def getWidth
      @width
   end
   def getHeight
      @height
   end
end


# create an object
box = Box.new(10, 20)


# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Area of the box is : 200

 

Explanation:

Anyone can call public methods. Methods are public by default except for initializing, which is always private.

Private Visibility

A private method is internal to a class's implementation and can only be called by other instance methods of the class (subclass). Private methods are invoked implicitly on self and cannot be explicitly invoked on an object.

If m is a private method, it must be invoked as m in functional style. You can't even write o.m or self.m.

Let’s see an example: 

#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end


   # instance method by default it is public
   def getArea
      getWidth() * getHeight
   end


   def getWidth
      @width
   end
   def getHeight
      @height
   end
   # make them private
   private :getWidth, :getHeight


end



# create an object
box = Box.new(10, 20)


# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
w = box.getWidth()
h = box.getHeight()
puts "Width & Height respectively ara: #{w} #{h} " 
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Area of the box is : 200
prog.rb:34:in `<main>': private method `getWidth' called for #<Box:0x0055759dc04758 @width=10, @height=20> (NoMethodError)

 

Explanation:

Here, When getArea method called getWidth and getHeight it was able to access these methods as getArea is inside the object, and when these private methods, called outside the object. They are not accessible. Therefore, Private methods cannot be accessed or viewed from outside the class. Only the class methods can access private members.

Protected Visibility

Like a private method, a protected method can only be called from within a class's or its subclasses' implementation. It differs from a private method in that it can be explicitly invoked on any instance of the class instead of only being implicitly invoked on self. A protected method, for example, can be used to define an accessor that allows instances of a class to share an internal state but prevents class users from accessing that state.

Let’s see an example: 

#!/usr/bin/ruby -w


# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end


   # instance method by default it is public
   def getArea
      getWidth() * getHeight
   end


   def getWidth
      @width
   end
   def getHeight
      @height
   end
   # make them private
   private :getWidth, :getHeight
   
    # make it protected
    protected :getArea

end


# create an object
box = Box.new(10, 20)


# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

prog.rb:35:in `<main>': protected method `getArea' called for #<Box:0x00560609d10b18 @width=10, @height=20> (NoMethodError)


Explanation:

 A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.

We've learned a lot of new concepts up to this point, so let's look at some Frequently Asked Questions related to them.

Frequently Asked Questions

What is method visibility?

Method Visibility in Ruby defines accessibility, i.e., whether other classes can use a specific field or invoke a specific method in a specific class. 

What is the order of method visibility in Ruby?

In Ruby, the method visibility restrictions are restricted in the following order: public > protected > private.

What does the public mean as a modifier?

Members of this modifier are accessible in such a way that they are visible to the entire world.

What does private mean as a modifier?

Members of this modifier are private in the sense that they are only visible to their own class.

What does protected mean as a modifier?

Members of this modifier are accessible in such a way that they are visible to their own package and subclasses.

Conclusion 

In this article, we have extensively discussed Method visibility in Ruby.

The explanation of the code was also provided by us in order to make your crystal clear about the topic, and I hope it helped you!

You can explore some more articles on RubyFor loop in RubyOperators in Ruby or see the Documentation of ruby, or access the Coding Ninjas Studio for our courses.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

Conclusion Image

Live masterclass