Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How Does Encapsulation Work in Ruby?
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
Advertisements