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
ruby中的容器,Array,hash,以及迭代器的作用实例
最新推荐文章于 2019-01-03 10:19:41 发布