如何在 Ruby 中使用封装?


封装是指将数据打包到一个单元中的功能。简单来说,它是一种将数据和操作数据代码打包的机制。在 Ruby 中,我们可以借助类实现封装。

我们考虑一个非常简单的示例,在其中将实现封装

示例 1

考虑如下所示的代码

Open Compiler
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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

让我们考虑另一个Ruby 封装示例。

Open Compiler
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

更新于: 12-4-2022

1 千次观看

开启你的 职业

完成课程以获得认证

开始
广告