Latest web development tutorials

루비 클래스 케이스

루비라는 클래스 고객을 생성합니다 다음은, 두 가지 방법을 선언합니다 :

  • 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, 고객 이름, 고객 주소를 보여주는 세 둔다 문으로 구성되어 있습니다. 특징으로, 문을 넣습니다 :

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. 이러한 방법으로, 당신은 클래스 변수를 고객의 총 수를 얻을 것이다.

이제 다음과 같이 두 개의 고객을 만듭니다

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

여기서 우리는 객체 고객, cust1 및 cust2의 두 클래스를 작성하고 필요한 매개 변수를 새로운 방법을 전달합니다. 초기화 메소드가 호출 될 때, 물체의 필요한 특성은 초기화된다.

객체를 만든 후에는 클래스의 메서드를 호출하는 두 개체를 사용해야합니다. 당신이 어떤 방법 또는 데이터 멤버를 호출하려면 다음과 같이 코드를 작성할 수 있습니다 :

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

# 创建对象
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