手机版
你好,游客 登录 注册
背景:
阅读新闻

简单的Ruby 类

[日期:2011-07-22] 来源:Linux社区  作者:cheungmine [字体:大 中 小]

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

 
  1. #模块声明, 类似于名称空间   
  2. module Animals  
  3.   
  4. class Animal  
  5.     # 类的默认构造函数   
  6.     def initialize(name, species)  
  7.         @name=name  
  8.         @species=species  
  9.     end  
  10.       
  11.     #getter for name attribute   
  12.     def name  
  13.         @name  
  14.     end  
  15.   
  16.     #setter for name attribute   
  17.     def  name=(nameVal)  
  18.         @name=nameVal  
  19.     end  
  20.       
  21.     #getter for species attribute   
  22.     def species  
  23.         @species  
  24.     end  
  25.   
  26.     #setter for species attribute   
  27.     def  species=(speciesVal)  
  28.         @species=speciesVal  
  29.     end  
  30. end  
  31.   
  32. # 类DogAnimal继承自Animal   
  33. class DogAnimal < Animal  
  34.     def initialize(voice)  
  35.         super("Dog", "mammal")  
  36.         @voice = voice  
  37.     end  
  38.       
  39.     #getter for voice attribute   
  40.     def voice  
  41.         @voice  
  42.     end  
  43.   
  44.     #setter for voice attribute   
  45.     def  voice=(voiceVal)  
  46.         @voice=voiceVal  
  47.     end  
  48. end  
  49.   
  50. end #module Animals   
  51.   
  52. cat = Animals::Animal.new("Cat", "mammal");  
  53. dog = Animals::DogAnimal.new("WangWang");  
  54.   
  55. 3.times{  
  56.     print cat.name + " is a " + cat.species + "\n"  
  57.     print dog.name + "'s voice is: " + dog.voice + "\n"  
  58. }  
  59.   
  60. =begin  
  61. #ruby命令行运行脚本   
  62. ruby c:\animals.rb  
  63.   
  64. 结果显示:  
  65. Cat is a mammal  
  66. Dog's voice is WangWang  
  67. Cat is a mammal  
  68. Dog's voice is WangWang  
  69. Cat is a mammal  
  70. Dog's voice is WangWang  
  71. =end  
linux
相关资讯       Ruby 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款