Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Ruby Access Control

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 565
    Comment on it

    The Access Controls provide us the method which allows us to set access to classes , methods and other members in Ruby. They help us to bind the components to maintain the security of the methods throughout the project.

     

    Ruby provides us with three types of access controls:

    1. Public
    2. Protected
    3. Private

     

    Public

    The public method can be accessed by everyone inside and outside the class. It means that any instance of the class is free to call them. By default, all methods are set to public.

    class Bike
      def bike_name
        "Avenger 220"         
      end
      private
        def bike_type
          "Cruiser"
        end
      protected
        def bike_chasis_number
          "AQZXS69870"
        end
    end
    b = Bike.new
    b.bike_name           #This will be called successfully.
    b.bike_type           #This Will give an access violation error 
    b.bike_chasis_number  #This will give an access violation error

    Private

    This can be accessed only inside its own class. If you try to access it outside the class it will give an error. Therefore private method can only be called inside the class in which it is defined and also the sub-classes of this class.

    class X
      def main_function
        function12
      end
      private
        def function12
          puts "This is from #{self.class}"
        end
      end
    class Y < X
      def main_function
        function12
      end
    end
    X.new.main_function # output will be: This is from X 
    Y.new.main_function # output will be: This is from Y

     Protected

    Protected methods are like private methods that can only be called by the objects of their own class or by the subclass of the class in which they are declared. They can explicitly be called by using the self-method.

    class X
      def main_function
        function12
      end
      protected
        def function12
          puts "This is from #{self.class}"
        end
      end
    class X < Y
      def main_function
        function12
      end
    end
    class Z < X
      def main_function
        self.function12
      end
    end
    X.new.main_function # output will give: This is from X 
    Y.new.main_function # output will give: This is from Y 
    Z.new.main_function # output will give: This is from Z 

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: