在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.属性的读写控制 class Man def initialize(name,sex) @name = name @age = 16 @sex = sex end # 只读 def get_name return @name end # 只写 def set_age(age) @age = age end # 读写 def get_sex return @sex end def set_sex(sex) @sex = sex end end t = Man.new("Jim","male"); puts t.get_name puts t.get_sex t.set_sex("man") puts t.get_sex t.set_age(22)
通过方法来实现属性的控制 2.还有一种简略的写法 class Man def initialize(name,sex) @name = name @age = 16 @sex = sex end # 只读 def name @name end # 只写 def age=(age)#这里等号不能有空格 @age = age end # 读写 def sex @sex end def sex=(sex) @sex = sex end end t = Man.new("Jim","male") puts t.name puts t.sex t.sex = "man" puts t.sex t.age = 22 puts t.age
结果: 3.垃圾收集 4.异常处理 s = 1 begin s = 1/0 puts s rescue puts "error!" end
结果:error!因为有错误捕捉到。 (2)重试语句 s = 1 begin s = 1/0 puts s rescue puts "error!" retry end
如果有错误,会一直报错下去 (3)抛出异常 begin raise "test" rescue puts "error!"+$! # retry end
结果: (4)结束清理 s = 1 begin s = 1/0 rescue puts "error!"+$! # retry ensure puts "finished!" end puts "------------" s = 1 begin s = 1/2 rescue puts "error!"+$! # retry ensure puts "finished!" end
结果:
小结: Ruby中的类使用跟java大同小异了 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论