Ruby-class-case-study

提供:Dev Guides
移動先:案内検索

Rubyクラスのケーススタディ

ケーススタディでは、CustomerというRubyクラスを作成し、2つのメソッドを宣言します-

  • 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_メソッドには、顧客ID、顧客名、顧客アドレスを表示する3つの_puts_ステートメントが含まれています。 putsステートメントは、次のようにテキストCustomer IDに続いて変数@ cust_idの値を1行で表示します-

puts "Customer id #@cust_id"

インスタンス変数のテキストと値を1行で表示する場合は、putsステートメントで変数名の前にハッシュ記号(#)を付ける必要があります。 テキストとインスタンス変数は、ハッシュ記号(#)とともに二重引用符で囲む必要があります。

2番目のメソッド、total_no_of_customersは、クラス変数@@ no_of_customersを含むメソッドです。 式@@ no_of_ customers + = 1は、メソッドtotal_no_of_customersが呼び出されるたびに、変数no_of_customersに1を追加します。 このようにして、クラス変数には常に顧客の総数が入ります。

今、次のように2人の顧客を作成します-

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

ここでは、Customerクラスの2つのオブジェクトをcust1およびcust2として作成し、新しいメソッドで必要なパラメーターを渡します。 初期化メソッドが呼び出され、オブジェクトの必要なプロパティが初期化されます。

オブジェクトが作成されたら、2つのオブジェクトを使用してクラスのメソッドを呼び出す必要があります。 あなたがメソッドまたは任意のデータメンバーを呼び出したい場合は、次のように書きます-

cust1.display_details()
cust1.total_no_of_customers()

オブジェクト名の後には常にドットが続き、その後にメソッド名またはデータメンバーが続きます。 cust1オブジェクトを使用して2つのメソッドを呼び出す方法を見てきました。 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