Ruby Encapsulation

        Encapsulation is one of the core principles of object-oriented programming, and it is the concept of hiding the internal state of an object from the outside world, and exposing only the methods and properties that are necessary to interact with the object. This helps to maintain the integrity and security of the object, as well as simplifying the interface that the object presents to the outside world.

        In Ruby, encapsulation is achieved through the use of access modifiers, which control the visibility of methods and properties of an object. There are three types of access modifiers in Ruby:

public - public methods and properties can be accessed from anywhere in the program, including outside the class definition.

private - private methods and properties can only be accessed from within the class definition, and not from outside.

protected - protected methods and properties can only be accessed from within the class definition, and also by subclasses of the class.

        Let's take an example of a class called Person that has three properties: name, age, and ssn. We want to make the name and age properties accessible to the outside world, but keep the ssn property hidden.

    class Person
      attr_accessor :name, :age

      def initialize(name, age, ssn)
        @name = name
        @age = age
        @ssn = ssn
      end

      def get_ssn
        @ssn
      end

      private

      def set_ssn(ssn)
        @ssn = ssn
      end
    end

        In this example, we use the attr_accessor method to create getter and setter methods for the name and age properties. We also define a get_ssn method to retrieve the ssn property, but we make it private so that it cannot be accessed from outside the class.

        We also define a set_ssn method to set the value of the ssn property, but we make it private so that it can only be accessed from within the class definition. This ensures that the ssn property is never exposed to the outside world, and can only be accessed or modified by methods within the class.

        Encapsulation helps to ensure that the internal state of an object is not accidentally modified or corrupted by external code. It also helps to simplify the interface that the object presents to the outside world, making it easier to understand and use.