Ruby 是純物件導向的語言,Ruby 中的一切都是以對象的形式出現。Ruby 中的每個值都是一個對象,即使是最原始的東西:字串、數字,甚至連 true 和 false 都是對象。類本身也是一個對象,是 Class 類的一個執行個體。本章將向您講解所有與 Ruby 物件導向相關的主要功能。
類用於指定對象的形式,它結合了資料標記法和方法,把資料整理成一個整齊的包。類中的資料和方法被稱為類的成員。
Ruby 類定義
當您定義一個類時,您實際是定義了一個資料類型的藍圖。這實際上並沒有定義任何的資料,而是定義了類的名稱意味著什麼,也就是說,定義了類的對象將由什麼組成,以及在該對象上能執行什麼操作。
類定義以關鍵字 class 開始,後跟類名稱,最後以一個 end 進行分隔表示終止該類定義。例如,我們使用關鍵字 class 來定義 Box 類,如下所示:
按照慣例,名稱必須以大寫字母開頭,如果包含多個單詞,每個單字首大寫,但此間沒有分隔字元(例如:CamelCase)。
定義 Ruby 對象
類提供了對象的藍圖,所以基本上,對象是根據類進行建立的。我們使用 new 關鍵字聲明類的對象。下面的語句聲明了類 Box 的兩個對象:
box1 = Box.newbox2 = Box.new
initialize 方法
initialize 方法是一個標準的 Ruby 類方法,與其他物件導向程式設計語言中的 constructor 工作原理類似。當您想要在建立對象的同時初始化一些類變數,initialize 方法就派上用場了。該方法帶有一系列參數,與其他 Ruby 方法一樣,使用該方法時,必須在前面放置 def 關鍵字,如下所示:
class Box def initialize(w,h) @width, @height = w, h endend
執行個體變數
執行個體變數是類屬性,它們在使用類建立對象時就變成對象的屬性。每個對象的屬性是單獨賦值的,和其他對象之間不共用值。在類的內部,是使用 @ 運算子訪問這些屬性,在類的外部,則是使用稱為訪問器方法的公用方法進行訪問。下面我們以上面定義的類 Box 為執行個體,把 @width 和 @height 作為類 Box 的執行個體變數。
class Box def initialize(w,h) # 給執行個體變數賦值 @width, @height = w, h endend
訪問器 & 設定器 方法
為了在類的外部使用變數,我們必須在訪問器方法內部定義這些變數,這些訪問器方法也被稱為擷取器方法。下面的執行個體示範了訪問器方法的用法:
#!/usr/bin/ruby -w # 定義類class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 訪問器方法 def printWidth @width end def printHeight @height endend # 建立對象box = Box.new(10, 20) # 使用訪問器方法x = box.printWidth()y = box.printHeight() puts "Width of the box is : #{x}"puts "Height of the box is : #{y}"
當上面的代碼執行時,它會產生以下結果:
Width of the box is : 10Height of the box is : 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 endend # 建立對象box = Box.new(10, 20) # 使用設定器方法box.setWidth = 30box.setHeight = 50 # 使用訪問器方法x = box.getWidth()y = box.getHeight() puts "Width of the box is : #{x}"puts "Height of the box is : #{y}"
當上面的代碼執行時,它會產生以下結果:
Width of the box is : 30Height of the box is : 50
執行個體方法
執行個體方法的定義與其他方法的定義一樣,都是使用 def 關鍵字,但它們只能通過類執行個體來使用,如下面執行個體所示。它們的功能不限於訪問執行個體變數,也能按照您的需求做更多其他的任務。
#!/usr/bin/ruby -w # 定義類class Box # constructor method def initialize(w,h) @width, @height = w, h end # 執行個體方法 def getArea @width * @height endend # 建立對象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" endend # 建立兩個對象box1 = Box.new(10, 20)box2 = Box.new(30, 100) # 調用類方法來輸出盒子計數Box.printCount()
當上面的代碼執行時,它會產生以下結果:
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)" # 對象的字串格式 endend # 建立對象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 :printAreaend # 建立對象box = Box.new(10, 20) # 調用執行個體方法a = box.getArea()puts "Area of the box is : #{a}" # 嘗試調用 protected 的執行個體方法box.printArea()
當上面的代碼執行時,它會產生以下結果。在這裡,第一種方法調用成功,但是第二方法會產生一個問題。
Area of the box is : 200test.rb:42: protected method `printArea' called for #<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)
類的繼承
繼承,是物件導向編程中最重要的概念之一。繼承允許我們根據另一個類定義一個類,這樣使得建立和維護應用程式變得更加容易。
繼承有助於重用代碼和快速執行,不幸的是,Ruby 不支援多繼承,但是 Ruby 支援 mixins。mixin 就像是多繼承的一個特定實現,在多繼承中,只有介面部分是可繼承的。
當建立類時,程式員可以直接指定新類繼承自某個已有類的成員,這樣就不用從頭編寫新的資料成員和成員函數。這個已有類被稱為基類或父類,新類被稱為衍生類別或子類。
Ruby 也提供了子類化的概念,子類化即繼承,下面的執行個體解釋了這個概念。擴充一個類的文法非常簡單。只要添加一個 < 字元和父類的名稱到類語句中即可。例如,下面定義了類 BigBox 是 Box 的子類:
#!/usr/bin/ruby -w # 定義類class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 執行個體方法 def getArea @width * @height endend # 定義子類class BigBox < Box # 添加一個新的執行個體方法 def printArea @area = @width * @height puts "Big box area is : #@area" endend # 建立對象box = BigBox.new(10, 20) # 輸出面積box.printArea()
當上面的代碼執行時,它會產生以下結果:
方法重載
雖然您可以在衍生類別中添加新的功能,但有時您可能想要改變已經在父類中定義的方法的行為。這時您可以保持方法名稱不變,重載方法的功能即可,如下面執行個體所示:
#!/usr/bin/ruby -w # 定義類class Box # 構造器方法 def initialize(w,h) @width, @height = w, h end # 執行個體方法 def getArea @width * @height endend # 定義子類class BigBox < Box # 改變已有的 getArea 方法 def getArea @area = @width * @height puts "Big box area is : #@area" endend # 建立對象box = BigBox.new(10, 20) # 使用重載的方法輸出面積box.getArea()
運算子多載
我們希望使用 + 運算子執行兩個 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) endend
凍結對象
有時候,我們想要防止對象被改變。在 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 endend # 建立對象box = Box.new(10, 20) # 讓我們凍結該對象box.freezeif( box.frozen? ) puts "Box object is frozen object"else puts "Box object is normal object"end # 現在嘗試使用設定器方法box.setWidth = 30box.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 objecttest.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 endend # 建立對象box = Box.new(10, 20) # 調用執行個體方法a = box.getArea()puts "Area of the box is : #{a}"puts Box::BOX_COMPANYputs "Box weight is: #{Box::BOXWEIGHT}"
當上面的代碼執行時,它會產生以下結果:
Area of the box is : 200TATA IncBox 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 endend # 使用 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 : 200test.rb:14: warning: instance variable @width not initializedtest.rb:14: warning: instance variable @height not initializedtest.rb:14:in `getArea': undefined method `*' for nil:NilClass (NoMethodError) from test.rb:29
類資訊
如果類定義是可執行代碼,這意味著,它們可在某個對象的上下文中執行,self 必須引用一些東西。讓我們來看看下面的執行個體:.
#!/usr/bin/ruby -w class Box # 輸出類資訊 puts "Type of self = #{self.type}" puts "Name of self = #{self.name}"end
當上面的代碼執行時,它會產生以下結果:
Type of self = ClassName of self = Box
這意味著類定義可通過把該類作為當前對象來執行,同時也意味著元類和父類中的該方法在方法定義執行期間是可用的。