在oop中,常见对象构造函数-constructor和析构函数-destructor,分别执行的是初始化和删除对象需要完成的任务。
在ruby中,有constructor但是没有destructor的概念,因为ruby有运转良好的垃圾回收机制。
继承inheritance:
继承是复用代码的方法
已经有一个通用类,当需要一个具体的类时,可以定义新类继承旧类的特性。
多态polymorphism,
不同对象对相同消息(或方法调用)做出不同相应的能力
----
分析示例程序
print "please enter a temperature and scale (C or F):"
str=gets #将输入保存
str.chomp! #使用chomp!方法去除str中保存的回车符
temp, scale= str.split(' ') #按照空格进行分割
abort "#{temp} is not a valid number." if temp !~/-?\d+/
#如果temp不是数字的话,终止程序,并提示" "
temp=temp.to_f #将temp转换成float类型
case scale #根据输入的c或者f进行计算
when "c","C" #如果输入的是摄氏度
f=1.8*temp + 32 #换算成华氏温度
when "F","f" #如果输入是华氏温度
c=(5.0/9.0)*(temp-32) #换算成摄氏度
else #如果在scale的位置输入了其他字符
abort "must specify C or F" #终止程序,并给出提示
end
if f.nil? #如果是从f转换成c,那么上面的f变量为nil
print "#{c} degrees C\n" #输出摄氏度
else #如果是c转换成f
print "#{f} degrees F\n" #输入华氏温度
end
str=gets #将输入保存
str.chomp! #使用chomp!方法去除str中保存的回车符
temp, scale= str.split(' ') #按照空格进行分割
abort "#{temp} is not a valid number." if temp !~/-?\d+/
#如果temp不是数字的话,终止程序,并提示" "
temp=temp.to_f #将temp转换成float类型
case scale #根据输入的c或者f进行计算
when "c","C" #如果输入的是摄氏度
f=1.8*temp + 32 #换算成华氏温度
when "F","f" #如果输入是华氏温度
c=(5.0/9.0)*(temp-32) #换算成摄氏度
else #如果在scale的位置输入了其他字符
abort "must specify C or F" #终止程序,并给出提示
end
if f.nil? #如果是从f转换成c,那么上面的f变量为nil
print "#{c} degrees C\n" #输出摄氏度
else #如果是c转换成f
print "#{f} degrees F\n" #输入华氏温度
end
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/66068,如需转载请自行联系原作者