2gua 发表于 2011-07-22 09:54

简单的Ruby 类

[转帖]来源:Linux社区作者:cheungmine

建立下面的脚本文件,命名为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   
      defname=(nameVal)
            @name=nameVal
      end
         
      #getter for species attribute   
      def species
            @species
      end
      
      #setter for species attribute   
      defspecies=(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   
      defvoice=(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

2gua 发表于 2011-07-25 13:54

呃,都没人理吗?

bugbugbug3 发表于 2011-07-25 18:12

setter 和 getter 为啥不用attr_accessor ? attr_accessor能更简洁一些。

2gua 发表于 2011-07-26 08:08

入门的教程吧,先从简单概念阐述起。

sykp241095 发表于 2011-07-26 10:20

写的真好

2gua 发表于 2011-07-26 12:43

楼上貌似很久没出现了。

sykp241095 发表于 2011-07-26 13:05

:-),很久没来这了,但期间实践了一些啊,http://huoxy.me/

2gua 发表于 2011-07-26 20:57

哦,你的博客啊,挺不错的啊。

i_love_ruby 发表于 2011-09-16 17:40

ding
页: [1]
查看完整版本: 简单的Ruby 类