美文网首页
一个ruby的类案例

一个ruby的类案例

作者: 风___________ | 来源:发表于2018-02-12 15:38 被阅读9次
    1. 定义
    #!/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()
    
    1. 运行脚本
    $ ruby main.rb
    
    1. 结果如下
    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
    

    相关文章

      网友评论

          本文标题:一个ruby的类案例

          本文链接:https://www.haomeiwen.com/subject/kbyltftx.html