如何在 Ruby 中使用封裝?
封裝是指將資料打包到一個單元中的功能。簡單來說,它是一種將資料和操作資料程式碼打包的機制。在 Ruby 中,我們可以藉助類實現封裝。
我們考慮一個非常簡單的示例,在其中將實現封裝。
示例 1
考慮如下所示的程式碼
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輸出
它將產生以下輸出 -
TutorialsPoint
示例 2
讓我們考慮另一個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()輸出
它將產生以下輸出 -
Customer id: 1 Customer name: Mike Customer address: Himalaya Pride Apartments, Noida Customer id: 2 Customer name: Rahul Customer address: New Empire road, LA
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP