Ruby 教程 之 Ruby 类案例 2

简介: Ruby 类案例

Ruby 教程 之 Ruby 类案例 2

Ruby 类案例

保存并执行代码
现在,把所有的源代码放在 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
这将产生以下结果:

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

目录
相关文章
|
2月前
|
数据采集 Web App开发 数据处理
Ruby网络爬虫教程:从入门到精通下载图片
Ruby网络爬虫教程:从入门到精通下载图片
|
3月前
|
JSON 数据格式 Ruby
|
3月前
|
JSON Ubuntu Linux
|
3月前
|
存储 JSON 数据格式
|
3月前
|
安全 Ruby
|
3月前
|
调度 Ruby
|
3月前
|
人工智能 BI 计算机视觉
|
3月前
|
Ruby
|
3月前
|
Ruby
|
3月前
|
调度 Ruby