一个测试脚本,既可以了解类的创建和初始化,还可以应用字符串的处理机制
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
class Car
@id
@name
def initialize(id, name)
@id = id
@name = name
end
def speeding(speed)
puts "ID:#{@id} " + @name + "超速#{speed}%..."
end
def driving
puts "ID:#{@id} " + @name + "行驶..."
end
def stopping
puts "ID:#{@id} " + @name + "泊车..."
end
end
car1 = Car.new(1, "Audi")
car1.driving
car2 = Car.new(2, "Benz")
car2.stopping
car3 = Car.new(3, "Jeep")
car3.speeding(20)
BEGIN {
puts "Initlizing Ruby program..."
}
END {
puts "Terminating Ruby program..."
}
运行结果: