Open In App

Private Classes in Ruby

The concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby.

Private Class

When a constant is declared private in Ruby, it means this constant can never be called with an explicit receiver, a private constant will be called only with an implicit receiver. So, in ruby private classes can be defined inside a class as a sub-class and declaring them into private constants, here this private class can be only accessed through the outer-class. Syntax:



 private_constant: class

Below is the example of Public class: 




# by default public
class Marvel
 
  # by default public
  class Guardians
      def Quill
          puts "Legendary outlaw"
        end
      def Groot
          puts "I am Groot"
        end
    end
 
  # by default public
  class Avengers
      def Tony
        puts "I am Iron-man"
      end
    end
end
Marvel::Avengers.new.Tony
Marvel::Guardians.new.Quill

Output:

I am Iron-man
Legendary outlaw

In the above example as the sub-classes Guardians and Avengers are public, both implicit and explicit users have access to it.




# Ruby program of accessing private class
# public
class Marvel
 
  # Private
  class Guardians
      def Quill
          puts "Legendary outlaw"
        end
      def Groot
          puts "I am Groot"
        end
    end
 
  # public  
  class Avengers
      def Tony
        puts "I am Iron-man"
      end
    end
 
# making Guardians class private
private_constant :Guardians
end
  
Marvel::Avengers.new.Tony
 
# throws an error(NameError)
Marvel::Guardians.new.Quill

Output:
I am Iron-man
main.rb:20:in `': private constant Marvel::Guardians referenced (NameError)




# Ruby program a private class accessed through the outer-class.
# public
class Marvel
 
  # private
  class Guardians
      def Quill
          puts "Legendary outlaw"
        end
      def Groot
          puts "I am Groot"
        end
    end
 
  # private  
  class Avengers
      def Tony
        puts "I am Iron-man"
      end
    end
 
# outer-class method accessing private classes    
def fury
    Guardians.new.Groot
    Avengers.new.Tony
end
private_constant :Guardians
private_constant :Avengers
end
 
# calls fury method in Marvel call.
Marvel.new.fury
 
# throws error as it is explicit accessing.
Marvel::Avengers.new.Tony
 
# throws error as it is explicit accessing.
Marvel::Guardians.new.Quill

Output:
I am Groot
I am Iron-man
main.rb:26:in `': private constant Marvel::Avengers referenced (NameError)

Note :Outer-class can never be private.


Article Tags :