对于您的案Example研究,您将创建一个名为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
The display_details method contains three puts statements, displaying the Customer ID, the Customer name, and the Customer address. The puts statement will display the text Customer id followed by the value of the variable @cust_id in a single line as follows −
puts "Customer id #@cust_id"
如果要在一行中显示变量的文本和值,则需要在puts语句中的变量名称前加上井号(#)。文本和变量以及井号(#)应该用双引号引起来。
The second method, total_no_of_customers, is a method that contains the class variable @@no_of_customers. The expression @@no_of_ customers+=1 adds 1 to the variable no_of_customers each time the method total_no_of_customers is called. In this way, you will always have the total number of customers in the class variable.
现在,创建两个客户,如下所示:
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
在这里,我们创建Customer类的两个对象cust1和cust2,并使用新方法传递必要的参数。调用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 # Create Objects cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methods 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
参考链接
https://www.learnfk.com/ruby/ruby-class-case-study.html
标签:Case,Customer,customers,cust,no,Study,无涯,id,name From: https://blog.51cto.com/u_14033984/8491454