Home »
Ruby programming
Encapsulation in Ruby
Ruby | Encapsulation: In this tutorial, we are going to learn about the encapsulation, how to achieve encapsulation with examples in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on May 05, 2020
In this article, we will study about Encapsulation. We know that Ruby is a pure object-oriented language and in every object-oriented language, encapsulation is considered as one of the important properties. So, let us understand encapsulation with the help of program codes and syntaxes.
Wrapping up the data into a single unit is known as Encapsulation. It can also be called as the procedure to bind code and the data which is affected by the code together. By applying encapsulation you can protect your data from being manipulated by another source. In simpler words, it can be considered as the mechanism which allows data only to be manipulated by the member functions of the class in which they are declared.
How to achieve Encapsulation?
You can achieve encapsulation by declaring all the variables of class as private( they are by default private) and all the member functions as public(they are by default public). Now, these variables will only be accessed by these public methods of the class.
Advantages of Encapsulation
- Easy to test code: Unit testing is the testing that is known to every programmer. After achieving encapsulation, unit testing becomes easy to be done.
- Decreases Redundancy: Encapsulation helps with making the code reusable. You can update the code as per the requirement of time.
- Data Hiding: Encapsulation facilitates data hiding which means that user will not be able to get an idea about the internal implementation of the class. The user will be unaware of where the data is being stored in the class.
Let us understand encapsulation with the help of an example:
=begin
Ruby program to demonstrate encapsulation
=end
class Bank
def initialize(id, nme, no, type)
@cust_id = id
@cust_name = nme
@ac_no = no
@cust_type = type
end
def display_details
puts "Customer id : #{@cust_id}"
puts "Customer name : #{@cust_name}"
puts "Customer no : #{@ac_no}"
puts "Customer type : #{@cust_type}"
end
end
customer1 = Bank.new("Cust101", "Rashmeet", "AC789", "Savings")
customer2 = Bank.new("Cust102", "Parmeet", "AC1789", "Savings")
customer3 = Bank.new("Cust103", "Jagmeet", "AC2789", "Savings")
customer1.display_details
customer2.display_details
customer3.display_details
Output
Customer id : Cust101
Customer name : Rashmeet
Customer no : AC789
Customer type : Savings
Customer id : Cust102
Customer name : Parmeet
Customer no : AC1789
Customer type : Savings
Customer id : Cust103
Customer name : Jagmeet
Customer no : AC2789
Customer type : Savings
Explanation:
In the above code you can observe that the member functions and data are only accessible through the object or instance of the class. Here the instances of class "Bank" are customer1, customer2 and customer3.