VOOZH about

URL: https://www.geeksforgeeks.org/ruby/method-visibility-in-ruby/

⇱ Method Visibility in Ruby - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Method Visibility in Ruby

Last Updated : 12 Jul, 2025
Method visibility in Ruby refers that instance methods can be public, private or protected. Methods are by default public unless they are explicitly declared private or protected. Method visibility is used in Ruby to achieve Data Abstraction i.e showing only required information and hiding the background details. Method visibility depends on the three types of access modifiers of a class in Ruby:
  • Public Access Modifier
  • Protected Access Modifier
  • Private Access Modifier
  • Public Access Modifier

    The methods of a class which are public are easily called from any part of the program. Example :#1Output:
    publicMethod1 called!
    publicMethod2 called!
    
    In the above, program two public methods publicMethod1() and publicMethod2() of the class Geeks are called.

    Protected Access Modifier

    The methods of a class which are declared protected can only be called from the class in which it is declared and the classes derived from it. Example :#2 Output:
    protectedMethod called!
    
    In the above program, the protectedMethod() of Parent class is not accessible directly, so it is called from the publicMethod() of the derived class Geeks.

    Private Access Modifier

    The methods of a class which are declared private are called within the class only, private access modifier is the most secure access modifier. Example :#3 Output:
    privateMethod called!
    
    In the above program, the privateMethod() of the Geeks class an not be called directly. So it is called from the publicMethod() of the class Geeks. Now let us look at another program which demonstrates Method Visibility. Example :#4 Output:
    Parent methods: 
    publicMethod1 called!
    protectedMethod called!
    privateMethod called!
    
    Child methods: 
    publicMethod1 called!
    protectedMethod called!
    Comment
    Article Tags: