Ruby 類案例

Ruby 類案例

下面將建立一個名為 Customer 的 Ruby 類,宣告兩個方法:

  • display_details:該方法用於顯示客戶的詳細資訊。
  • total_no_of_customers:該方法用於顯示在系統中建立的客戶總數量。

例項

#!/usr/bin/ruby class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end

display_details 方法包含了三個 puts 語句,顯示了客戶 ID、客戶名字和客戶地址。其中,puts 語句:

puts "Customer id #@cust_id"

將在一個單行上顯示文字 Customer id 和變數 @cust_id 的值。

當您想要在一個單行上顯示例項變數的文字和值時,您需要在 puts 語句的變數名前面放置符號(#)。文字和帶有符號(#)的例項變數應使用雙引號標記。

第二個方法,total_no_of_customers,包含了類變數 @@no_of_customers。表示式 @@no_of_ customers+=1 在每次呼叫方法 total_no_of_customers 時,把變數 no_of_customers 加 1。通過這種方式,您將得到類變數中的客戶總數量。

現在建立兩個客戶,如下所示:

cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

在這裡,我們建立了 Customer 類的兩個物件,cust1 和 cust2,並向 new 方法傳遞必要的引數。當 initialize 方法被呼叫時,物件的必要屬性被初始化。

一旦物件被建立,您需要使用兩個物件來呼叫類的方法。如果您想要呼叫方法或任何資料成員,您可以編寫程式碼,如下所示:

cust1.display_details() cust1.total_no_of_customers()

物件名稱後總是跟著一個點號,接著是方法名稱或資料成員。我們已經看到如何使用 cust1 物件呼叫兩個方法。使用 cust2 物件,您也可以呼叫兩個方法,如下所示:

cust2.display_details() cust2.total_no_of_customers()

儲存並執行程式碼

現在,把所有的原始碼放在 main.rb 檔案中,如下所示:

例項

#!/usr/bin/ruby class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end # 建立物件 cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # 呼叫方法 cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers()

嘗試一下 ?

接著,執行程式,如下所示:

$ ruby main.rb

這將產生以下結果:

Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Total number of customers: 1
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Total number of customers: 2