Home »
Ruby Tutorial
Private Classes in Ruby
By IncludeHelp Last updated : November 16, 2024
In this tutorial, we will see the concept of private classes in Ruby. Though in Ruby, the concept of private classes is a little bit different in comparison with other languages. We will understand the concept of private classes with the help of syntaxes and examples in the rest of the content.a
Ruby Private Classes
In Ruby language, there exists keyword like private, protected and public but they do not provide any help while working with classes that we used to get in other languages.
They are differentiated by the way of calling them in the program code because all the classes are considered as objects in Ruby. Private classes can be understood as sub-class and they are declared with the help of private constants. You will have to use outer classes if you want to access the private classes. If a class is declared private then it can never be invoked with an explicit receiver, you will always have to invoke them with an implicit receiver. Ruby does not permit you to make an outer class private.
Syntax
private_constant: class_name
Example 1
=begin
Ruby program to demonstrate private classes
=end
class Outer
class Inner
def prnt1
puts "Hello from Includehelp.com"
end
def prnt2
puts "Corona Go! Go Corona"
end
end
private_constant :Inner
end
Object1 = Outer::Inner.new
Object1.prnt2
Output
private constant Outer::Inner referenced
(repl):18:in `<main>'
Explanation
In the above code, you can observe that the interpreter is throwing an error because we are explicit users and cannot access them in this manner.
How you can access a private class with the help of outer-class?
Example 2
=begin
Ruby program to demonstrate private classes
=end
class Outer
class Inner
def prnt1
puts "Hello from Includehelp.com"
end
def prnt2
puts "Corona Go! Go Corona"
end
end
private_constant :Inner
def ob
ob1 = Inner.new
ob1.prnt1
ob1.prnt2
end
end
Object1 = Outer.new
Object1.ob
Output
Hello from Includehelp.com
Corona Go! Go Corona
Explanation
In the above code, you can observe how you can access a private class or sub-class with the help of the public class? We have created a public method ob in which we are creating an instance of the private class Inner and invoking its methods with the help of that instance or object. This is the only way through which you can access the inner class or private class.