top
Loading...
Ruby 面向對象

Ruby 面向對象

Ruby 是純面向對象的語言,Ruby 中的一切都是以對象的形式出現。Ruby 中的每個值都是一個對象,即使是最原始的東西:字符串、數字,甚至連 true 和 false 都是對象。類本身也是一個對象,是 Class 類的一個實例。本章將向您講解所有與 Ruby 面向對象相關的主要功能。

類用於指定對象的形式,它結合了數據表示法和方法,把數據整理成一個整齊的包。類中的數據和方法被稱為類的成員。

Ruby 類定義

當您定義一個類時,您實際是定義了一個數據類型的藍圖。這實際上併沒有定義任何的數據,而是定義了類的名稱意味著什么,也就是說,定義了類的對象將由什么組成,以及在該對象上能執行什么操作。

類定義以關鍵字 class 開始,後跟類名稱,最後以一個 end 進行分隔表示終止該類定義。例如,我們使用關鍵字 class 來定義 Box 類,如下所示:

class Box code end

按照慣例,名稱必須以大寫字母開頭,如果包含多個單詞,每個單詞首字母大寫,但此間沒有分隔符(例如:CamelCase)。

定義 Ruby 對象

類提供了對象的藍圖,所以基本上,對象是根據類進行創建的。我們使用 new 關鍵字聲明類的對象。下面的語句聲明了類 Box 的兩個對象:

box1 = Box.new box2 = Box.new

initialize 方法

initialize 方法是一個標准的 Ruby 類方法,是類的構造函數,與其他面向對象編程語言中的 constructor 工作原理類似。當您想要在創建對象的同時初始化一些類變量,initialize 方法就派上用場了。該方法帶有一系列參數,與其他 Ruby 方法一樣,使用該方法時,必須在前面放置 def 關鍵字,如下所示:

class Box def initialize(w,h) @width, @height = w, h end end

實例變量

實例變量是類屬性,它們在使用類創建對象時就變成對象的屬性。每個對象的屬性是單獨賦值的,和其他對象之間不共享值。在類的內部,是使用 @ 運算符訪問這些屬性,在類的外部,則是使用稱為訪問器方法公共方法進行訪問。下面我們以上面定義的類 Box 為實例,把 @width 和 @height 作為類 Box 的實例變量。

class Box def initialize(w,h) # 給實例變量賦值 @width, @height = w, h end end

訪問器(getter) & 設置器(setter)方法

為了在類的外部讀取類中已定義的變量,我們可以通過定義訪問器(getter)方法來訪問。下面的實例演示了訪問器方法的用法:

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造函數 def initialize(w,h) @width, @height = w, h end # 訪問器方法 def printWidth @width end def printHeight @height end end # 創建對象,初始化盒子的高度與寬度 box = Box.new(10, 20) # 使用訪問器方法 x = box.printWidth() y = box.printHeight() puts "盒子寬度 : #{x}" puts "盒子高度 : #{y}"

當上面的代碼執行時,它會產生以下結果:

盒子寬度 : 10
盒子高度 : 20

與用於訪問變量值的訪問器方法類似,Ruby 提供了一種在類的外部將參數傳入類中已定義的變量,也就是所謂的設置器方法,定義如下:

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 訪問器方法 def getWidth @width end def getHeight @height end # 設置器方法 def setWidth=(value) @width = value end def setHeight=(value) @height = value end end # 創建對象 box = Box.new(10, 20) # 使用設置器方法 box.setWidth = 30 box.setHeight = 50 # 使用訪問器方法 x = box.getWidth() y = box.getHeight() puts "盒子寬度 : #{x}" puts "盒子高度 : #{y}"

當上面的代碼執行時,它會產生以下結果:

盒子寬度 : 30
盒子高度 : 50

由於兩種方法非常常用,Ruby 定義了 attr_accessor :variable_name、attr_reader :variable_name、attr_writer :variable_name 三種屬性聲明方法。其中:accessor=reader+writer

同時注意:變量名前一定要帶 : ,變量名之間要用 , 分割。

實例方法

實例方法的定義與其他方法的定義一樣,都是使用 def 關鍵字,但它們只能通過類實例來使用,如下面實例所示。它們的功能不限於訪問實例變量,也能按照您的需求做更多其他的任務。

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造方法 def initialize(w,h) @width, @height = w, h end # 實例方法 def getArea @width * @height end end # 創建對象 box = Box.new(10, 20) # 調用實例方法 a = box.getArea() puts "Area of the box is : #{a}"

當上面的代碼執行時,它會產生以下結果:

Area of the box is : 200

類方法 & 類變量

類變量是在類的所有實例中共享的變量。換句話說,類變量的實例可以被所有的對象實例訪問。類變量以兩個 @ 字符(@@)作為前綴,類變量必須在類定義中被初始化,如下面實例所示。

類方法使用 def self.methodname() 定義,類方法以 end 分隔符結尾。類方法可使用帶有類名稱的 classname.methodname 形式調用,如下面實例所示:

實例

#!/usr/bin/ruby -w class Box # 初始化類變量 @@count = 0 def initialize(w,h) # 給實例變量賦值 @width, @height = w, h @@count += 1 end def self.printCount() puts "Box count is : #@@count" end end # 創建兩個對象 box1 = Box.new(10, 20) box2 = Box.new(30, 100) # 調用類方法來輸出盒子計數 Box.printCount()

當上面的代碼執行時,它會產生以下結果:

Box count is : 2

to_s 方法

您定義的任何類都有一個 to_s 實例方法來返回對象的字符串表示形式。下面是一個簡單的實例,根據 width 和 height 表示 Box 對象:

實例

#!/usr/bin/ruby -w class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 定義 to_s 方法 def to_s "(w:#@width,h:#@height)" # 對象的字符串格式 end end # 創建對象 box = Box.new(10, 20) # 自動調用 to_s 方法 puts "String representation of box is : #{box}"

當上面的代碼執行時,它會產生以下結果:

String representation of box is : (w:10,h:20)

訪問控製

Ruby 為您提供了三個級別的實例方法保護,分別是 public、private 或 protected。Ruby 不在實例和類變量上應用任何訪問控製。

  • Public 方法: Public 方法可被任意對象調用。默認情況下,方法都是 public 的,除了 initialize 方法總是 private 的。
  • Private 方法: Private 方法不能從類外部訪問或查看。只有類方法可以訪問私有成員。
  • Protected 方法: Protected 方法只能被類及其子類的對象調用。訪問也只能在類及其子類內部進行。

下面是一個簡單的實例,演示了這三種修飾符的語法:

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 實例方法默認是 public 的 def getArea getWidth() * getHeight end # 定義 private 的訪問器方法 def getWidth @width end def getHeight @height end # make them private private :getWidth, :getHeight # 用於輸出面積的實例方法 def printArea @area = getWidth() * getHeight puts "Big box area is : #@area" end # 讓實例方法是 protected 的 protected :printArea end # 創建對象 box = Box.new(10, 20) # 調用實例方法 a = box.getArea() puts "Area of the box is : #{a}" # 嘗試調用 protected 的實例方法 box.printArea()

當上面的代碼執行時,它會產生以下結果。在這里,第一種方法調用成功,但是第二方法會產生一個問題。

Area of the box is : 200
test.rb:42: protected method `printArea' called for #
<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)

類的繼承

繼承,是面向對象編程中最重要的概念之一。繼承允許我們根據另一個類定義一個類,這樣使得創建和維護應用程序變得更加容易。

繼承有助於重用代碼和快速執行,不幸的是,Ruby 不支持多繼承,但是 Ruby 支持 mixins。mixin 就像是多繼承的一個特定實現,在多繼承中,只有接口部分是可繼承的。

當創建類時,程序員可以直接指定新類繼承自某個已有類的成員,這樣就不用從頭編寫新的數據成員和成員函數。這個已有類被稱為基類或父類,新類被稱為派生類或子類

Ruby 也提供了子類化的概念,子類化即繼承,下面的實例解釋了這個概念。擴展一個類的語法非常簡單。只要添加一個 < 字符和父類的名稱到類語句中即可。例如,下面定義了類 BigBoxBox 的子類:

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 實例方法 def getArea @width * @height end end # 定義子類 class BigBox < Box # 添加一個新的實例方法 def printArea @area = @width * @height puts "Big box area is : #@area" end end # 創建對象 box = BigBox.new(10, 20) # 輸出面積 box.printArea()

當上面的代碼執行時,它會產生以下結果:

Big box area is : 200

方法重載

雖然您可以在派生類中添加新的功能,但有時您可能想要改變已經在父類中定義的方法的行為。這時您可以保持方法名稱不變,重載方法的功能即可,如下面實例所示:

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 實例方法 def getArea @width * @height end end # 定義子類 class BigBox < Box # 改變已有的 getArea 方法 def getArea @area = @width * @height puts "Big box area is : #@area" end end # 創建對象 box = BigBox.new(10, 20) # 使用重載的方法輸出面積 box.getArea()

以上實例運行輸出結果為:

Big box area is : 200

運算符重載

我們希望使用 + 運算符執行兩個 Box 對象的向量加法,使用 * 運算符來把 Box 的 width 和 height 相乘,使用一元運算符 - 對 Box 的 width 和 height 求反。下面是一個帶有數學運算符定義的 Box 類版本:

class Box def initialize(w,h) # 初始化 width 和 height @width,@height = w, h end def +(other) # 定義 + 來執行向量加法 Box.new(@width + other.width, @height + other.height) end def -@ # 定義一元運算符 - 來對 width 和 height 求反 Box.new(-@width, -@height) end def *(scalar) # 執行標量乘法 Box.new(@width*scalar, @height*scalar) end end

凍結對象

有時候,我們想要防止對象被改變。在 Object 中,freeze 方法可實現這點,它能有傚地把一個對象變成一個常量。任何對象都可以通過調用 Object.freeze 進行凍結。凍結對象不能被修改,也就是說,您不能改變它的實例變量。

您可以使用 Object.frozen? 方法檢查一個給定的對象是否已經被凍結。如果對象已被凍結,該方法將返回 true,否則返回一個 false 值。下面的實例解釋了這個概念:

實例

#!/usr/bin/ruby -w # 定義類 class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 訪問器方法 def getWidth @width end def getHeight @height end # 設置器方法 def setWidth=(value) @width = value end def setHeight=(value) @height = value end end # 創建對象 box = Box.new(10, 20) # 讓我們凍結該對象 box.freeze if( box.frozen? ) puts "Box object is frozen object" else puts "Box object is normal object" end # 現在嘗試使用設置器方法 box.setWidth = 30 box.setHeight = 50 # 使用訪問器方法 x = box.getWidth() y = box.getHeight() puts "Width of the box is : #{x}" puts "Height of the box is : #{y}"

當上面的代碼執行時,它會產生以下結果:

Box object is frozen object
test.rb:20:in `setWidth=': can't modify frozen object (TypeError)
        from test.rb:39

類常量

您可以在類的內部定義一個常量,通過把一個直接的數值或字符串值賦給一個變量來定義的,常量的定義不需要使用 @ 或 @@。按照慣例,常量的名稱使用大寫。

一旦常量被定義,您就不能改變它的值,您可以在類的內部直接訪問常量,就像是訪問變量一樣,但是如果您想要在類的外部訪問常量,那么您必須使用 classname::constant,如下面實例所示。

實例

#!/usr/bin/ruby -w # 定義類 class Box BOX_COMPANY = "TATA Inc" BOXWEIGHT = 10 # 構造器方法 def initialize(w,h) @width, @height = w, h end # 實例方法 def getArea @width * @height end end # 創建對象 box = Box.new(10, 20) # 調用實例方法 a = box.getArea() puts "Area of the box is : #{a}" puts Box::BOX_COMPANY puts "Box weight is: #{Box::BOXWEIGHT}"

當上面的代碼執行時,它會產生以下結果:

Area of the box is : 200
TATA Inc
Box weight is: 10

類常量可被繼承,也可像實例方法一樣被重載。

使用 allocate 創建對象

可能有一種情況,您想要在不調用對象構造器 initialize 的情況下創建對象,即,使用 new 方法創建對象,在這種情況下,您可以調用 allocate 來創建一個未初始化的對象,如下面實例所示:

實例

#!/usr/bin/ruby -w # 定義類 class Box attr_accessor :width, :height # 構造器方法 def initialize(w,h) @width, @height = w, h end # 實例方法 def getArea @width * @height end end # 使用 new 創建對象 box1 = Box.new(10, 20) # 使用 allocate 創建兩一個對象 box2 = Box.allocate # 使用 box1 調用實例方法 a = box1.getArea() puts "Area of the box is : #{a}" # 使用 box2 調用實例方法 a = box2.getArea() puts "Area of the box is : #{a}"

當上面的代碼執行時,它會產生以下結果:

Area of the box is : 200
test.rb:14: warning: instance variable @width not initialized
test.rb:14: warning: instance variable @height not initialized
test.rb:14:in `getArea': undefined method `*' 
   for nil:NilClass (NoMethodError) from test.rb:29

類信息

Ruby的 self 和 Java 的 this 有相似之處,但又大不相同。Java的方法都是在實例方法中引用,所以this一般都是指向當前對象的。而Ruby的代碼逐行執行,所以在不同的上下文(context)self就有了不同的含義。讓我們來看看下面的實例:.

實例

#!/usr/bin/ruby -w class Box # 輸出類信息 puts "Class of self = #{self.class}" puts "Name of self = #{self.name}" end

當上面的代碼執行時,它會產生以下結果:

Class of self = Class
Name of self = Box

這意味著類定義可通過把該類作為當前對象來執行,同時也意味著元類和父類中的該方法在方法定義執行期間是可用的。

北斗有巢氏 有巢氏北斗