先看代码:
Song.rb
- class Song
- def initialize(name, artist, duration)
- @name = name
- @artist = artist
- @duration = duration
- end
- def to_s
- "Song: #@name--@artist (#@duration)"
- end
- end
- class KaraokeSong < Song
- def initialize(name, artist, duration, lyrics)
- super(name, artist, duration)
- @lyrics = lyrics
- end
- def to_s
- super + " [#@lyrics]"
- end
- end
- #song = KaraokeSong.new("shenbin", "fnl", 260, "And now, the...")
- #puts song.to_s
- #puts song.inspect
SongList.rb
- 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]
- end
- end
Test_song_list.rb
- require "test/unit"
- require "Song.rb"
- require "SongList.rb"
- class TestSongList < Test::Unit::TestCase
- def test_delete
- list = SongList.new
- s1 = Song.new('t1', 'a1', 1)
- s2 = Song.new('t2', 'a2', 2)
- s3 = Song.new('t3', 'a3', 3)
- s4 = Song.new('t4', 'a4', 4)
- list.append(s1).append(s2).append(s3).append(s4)
- assert_equal(s1, list[0])
- assert_equal(s3, list[2])
- assert_nil(list[4])
- 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
运行后输出:
Loaded suite Test_song_list
Started
.
Finished in 0.0 seconds.
1 tests, 8 assertions, 0 failures, 0 errors