English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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 문은:

puts "Customer id @cust_id"

문자 Customer id와 변수 @cust_id의 값을 하나의 단一行에 표시합니다.

하나의 단一行에 예제 변수의 텍스트와 값을 표시하려면, puts 문의 변수 이름 앞에 기호(#)를 두고, 텍스트와 기호(#)를 포함한 예제 변수는 따옴표로 표시해야 합니다.

두 번째 메서드인 total_no_of_customers는 클래스 변수 @@no_of_customers를 포함하고 있습니다. @@no_of_ 표현식 customers+=1 total_no_of_customers 메서드를 호출할 때마다, 변수 no_of_customers를 추가합니다 1이렇게 하면 클래스 변수에 있는 고객 총 수를 얻을 수 있습니다.

이제 두 명의 고객을 생성하세요, 다음과 같이:

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

여기서, Customer 클래스의 두 가지 객체를 생성했습니다, cust1 하고 cust2new 메서드에 필요한 매개변수를 전달합니다. initialize 메서드가 호출되면, 객체의 필요한 속성이 초기화됩니다.

객체가 생성되면, 두 가지 객체를 사용하여 클래스 메서드를 호출해야 합니다. 메서드나 어떤 데이터 멤버를 호출하려면 다음과 같은 코드를 작성할 수 있습니다:

cust1.display_details()
cust1.total_no_of_customers()

객체 이름 뒤에는 항상 점(.)이 따르며, 그 다음에 메서드 이름이나 데이터 멤버가 옵니다. 이미 cust를 사용하는 방법을 보았습니다1 객체를 호출하여 두 가지 메서드를 호출합니다. 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
 
# 创建对象
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()

그런 다음, 프로그램을 실행합니다. 다음과 같이 실행합니다:

$ ruby main.rb

이렇게 되면 다음과 같은 결과가 나타납니다:

고객 ID 1
고객 이름 John
고객 주소 Wisdom Apartments, Ludhiya
고객 수 총 1
고객 ID 2
고객 이름 Poul
고객 주소 New Empire road, Khandala
고객 수 총 2