Latest web development tutorials

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

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

為了在類的外部使用變量,我們必須在訪問器方法內部定義這些變量,accessor其實相當於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 "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

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

Width of the box is : 10
Height 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
   end
end

# 创建对象
box = Box.new(10, 20)

# 使用设置器方法
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}"

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

Width of the box is : 30
Height of the box is : 50

實例方法

實例方法的定義與其他方法的定義一樣,都是使用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

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