下面將創(chuàng)建一個(gè)名為 Customer 的 Ruby 類,聲明兩個(gè)方法:
display_details:該方法用于顯示客戶的詳細(xì)信息。
total_no_of_customers:該方法用于顯示在系統(tǒng)中創(chuàng)建的客戶總數(shù)量。
#!/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 方法包含了三個(gè) puts 語(yǔ)句,顯示了客戶 ID、客戶名字和客戶地址。其中,puts 語(yǔ)句:
puts "Customer id #@cust_id"
將在一個(gè)單行上顯示文本 Customer id 和變量 @cust_id 的值。
當(dāng)您想要在一個(gè)單行上顯示示例變量的文本和值時(shí),您需要在 puts 語(yǔ)句的變量名前面放置符號(hào)(#)。文本和帶有符號(hào)(#)的示例變量應(yīng)使用雙引號(hào)標(biāo)記。
第二個(gè)方法,total_no_of_customers,包含了類變量 @@no_of_customers。表達(dá)式 @@no_of_ customers+=1 在每次調(diào)用方法 total_no_of_customers 時(shí),把變量 no_of_customers 加 1。通過這種方式,您將得到類變量中的客戶總數(shù)量。
現(xiàn)在創(chuàng)建兩個(gè)客戶,如下所示:
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
在這里,我們創(chuàng)建了 Customer 類的兩個(gè)對(duì)象,cust1 和 cust2,并向 new 方法傳遞必要的參數(shù)。當(dāng) initialize 方法被調(diào)用時(shí),對(duì)象的必要屬性被初始化。
一旦對(duì)象被創(chuàng)建,您需要使用兩個(gè)對(duì)象來調(diào)用類的方法。如果您想要調(diào)用方法或任何數(shù)據(jù)成員,您可以編寫代碼,如下所示:
cust1.display_details() cust1.total_no_of_customers()
對(duì)象名稱后總是跟著一個(gè)點(diǎn)號(hào),接著是方法名稱或數(shù)據(jù)成員。我們已經(jīng)看到如何使用 cust1 對(duì)象調(diào)用兩個(gè)方法。使用 cust2 對(duì)象,您也可以調(diào)用兩個(gè)方法,如下所示:
cust2.display_details() cust2.total_no_of_customers()
現(xiàn)在,把所有的源代碼放在 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 # 創(chuàng)建對(duì)象 cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # 調(diào)用方法 cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers()
接著,運(yùn)行程序,如下所示:
$ ruby main.rb
這將產(chǎn)生以下結(jié)果:
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