Latest web development tutorials

Rubyのクラスケース

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 "Customer id #@cust_id"

顧客IDは、単一の行にテキストと変数@cust_id値を表示しました。

あなたは、単一の行にテキストと値のインスタンス変数を表示したいときは、変数名を入れ文の前にある記号(#)を配置する必要があります。 記号(#)でテキストとインスタンス変数は、二重引用符を使用する必要があります。

第二の方法は、total_no_of_customersは、クラス変数@@ no_of_customersが含まれています。 式@@それぞれの呼び出し方法total_no_of_customers時の+ = 1 no_of_顧客に加え、変数no_of_customers 1。 この方法では、クラス変数に顧客の総数を取得します。

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

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

ここでは、オブジェクトの顧客、CUST1とcust2の2つのクラスを作成して、必要なパラメータの新しいメソッドを渡します。 initializeメソッドが呼び出されると、オブジェクトの必要な属性が初期化されます。

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

cust1.display_details()
cust1.total_no_of_customers()

オブジェクト名は常にドットが続いた後、メソッドまたはデータメンバーの名前が続きます。 我々は2つのメソッドを呼び出す方法をCUST1オブジェクト見てきました。 次のようにcust2オブジェクトを使用して、あなたはまた、2つのメソッドを呼び出すことができます。

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()

次に、以下のように、プログラムを実行します。

$ルビー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