ruby中的容器,Array,hash,以及迭代器的作用实例

ruby中的array,hash 和容器
  (1)创建一个歌曲列表
  class Song 
    def initialize(name,artist,duration)
        @name = name
        @artist = artist
        @duration = duration
    end
    attr_reader:name,:artist,:duration
    attr_writer:name,:artist,:duration
  end
  #创建一个容器,功能与Array,hash相同
  class SongList
    def initialize
        @songs = Array.new
    end
    def append(song)
        @songs.push(song)#添加
        self
    end
    def delete_first
        @songs.shift#删除第一个
    end
    def delete_last
        @songs.pop#删除最后一个
    end
    def [](index)
        @songs[index]#查询index位置的元素
    end
  end
  #利用了Array的函数实现容器功能
    编写测试类,使用TestUnit测试框架
    require 'test/unit'
    class TestSongList < Test::Unit::TestCase
      def test_delete
        list = SongList.new
        s1 = Song.new("a","b",11);
        s2 = Song.new("a","b",22);
        s3 = Song.new("a","b",33);
        s4 = Song.new("a","b",44);
        list.append(s1).append(s2).append(s3).append(s4)
        assert_equal(s1,list[0])
        assert_equal(s3,list[2])
        assert_equal(list[9])
        
        assert_equal(s1,list.delete_first)
        assert_equal(s2,list.delete_first)
        assert_equal(s4,list.delete_last)
        assert_equal(s3,list.delete_last)
        assert_nil(list.delete_last)
      end
    end
    
    
15.ruby中迭代器的作用
   实例一:检索歌曲(写一函数)
   class SongList
     def with_title(title)
        for i in 0..@songs.length
            return @songs[i] if @songs[i].name == title
            #if语句的简写
        end
        return nil
     end
     def with_title2(title)
        @songs.find{|song| title == song.name}
        #迭代器检索
     end
   end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值