How Does Encapsulation Work in Ruby?

RubyServer Side ProgrammingProgramming

Encapsulation is the ability to wrap the data into a single unit. In simple terms, it's a mechanism to wrap data and the code that manipulates the data. In Ruby, we can achieve encapsulation with the help of classes.

Let's consider a very simple example where we will implement encapsulation.

Example 1

Consider the code shown below

class Document
   attr_accessor :name

   def initialize(name)
      @name = name
   end

   def set_name(name)
      @name = name
   end
end

d = Document.new('TP')
d.set_name('TutorialsPoint')

puts d.name

Output

It will produce the following output −

TutorialsPoint

Example 2

Let's consider one more example of Encapsulation in Ruby.

class EncapsulationExample
   def initialize(id, name, addr)
      # Instance Variables
      @cust_id = id
      @cust_name = name
      @cust_addr = addr
   end

   # displaying result
   def print_details()
      puts "Customer id: #@cust_id"
      puts "Customer name: #@cust_name"
      puts "Customer address: #@cust_addr"
   end
end

# Create the Objects
cust1 = EncapsulationExample.new("1", "Mike", "Himalaya Pride Apartments, Noida")
cust2 = EncapsulationExample.new("2", "Rahul", "New Empire road, LA")

# Call the Methods
cust1.print_details()
cust2.print_details()

Output

It will produce the following output −

Customer id: 1
Customer name: Mike
Customer address: Himalaya Pride Apartments, Noida
Customer id: 2
Customer name: Rahul
Customer address: New Empire road, LA
raja
Updated on 12-Apr-2022 07:53:34

Advertisements