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 语句将在一行中显示文本 Customer id 后跟变量 @cust_id 的值,如下所示 −

puts "Customer id #@cust_id"

当您想在一行中显示文本和实例变量的值时,您需要在 puts 语句中的变量名称前加上井号 (#)。 文本和实例变量以及井号 (#) 应括在双引号中。

第二种方法,total_no_of_customers,是一个包含类变量 @@no_of_customers 的方法。每次调用方法 total_no_of_customers 时,表达式 @@no_of_customers+=1 将变量 no_of_customers 加 1。这样,您将始终在类变量中拥有客户总数。

现在,创建两个客户如下 −

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)
      @@no_of_customers += 1
      @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()
      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()

cust3 = Customer.new("3", "Raghu", "Madapur, Hyderabad")
cust4 = Customer.new("4", "Rahman", "Akkayya palem, Vishakhapatnam")
cust4.total_no_of_customers()

现在,运行这个程序如下 −

$ ruby main.rb

这将产生以下结果 −

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

❮ Ruby 类和对象