简单的Ruby 类

简单的Ruby 类

建立下面的脚本文件,命名为C:\animals.rb,使用notepad++,选择格式为以UTF-8无BOM格式编码保存:

#模块声明, 类似于名称空间 module Animals class Animal # 类的默认构造函数 def initialize(name, species) @name=name @species=species end #getter for name attribute def name @name end #setter for name attribute def name=(nameVal) @name=nameVal end #getter for species attribute def species @species end #setter for species attribute def species=(speciesVal) @species=speciesVal end end # 类DogAnimal继承自Animal class DogAnimal < Animal def initialize(voice) super("Dog", "mammal") @voice = voice end #getter for voice attribute def voice @voice end #setter for voice attribute def voice=(voiceVal) @voice=voiceVal end end end #module Animals cat = Animals::Animal.new("Cat", "mammal"); dog = Animals::DogAnimal.new("WangWang"); 3.times{ print cat.name + " is a " + cat.species + "\n" print dog.name + "'s voice is: " + dog.voice + "\n" } =begin #ruby命令行运行脚本 ruby c:\animals.rb 结果显示: Cat is a mammal Dog's voice is WangWang Cat is a mammal Dog's voice is WangWang Cat is a mammal Dog's voice is WangWang =end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值