私は初心者で、テストに合格するのに苦労しています。アーティスト、曲、ジャンルの 3 つのクラスがあります。私が合格させようとしているテストは以下の通りです:
test 'A genre has many artists' do
genre = Genre.new.tap{|g| g.name = 'rap'}
[1,2].each do
artist = Artist.new
song = Song.new
song.genre = genre
artist.add_song(song)
end
assert_equal genre.artists.count, 2
end
これは私のアーティスト クラスです。add_song メソッドは微調整が必要なものです。曲がアーティストに追加されると、新しい Genre オブジェクトをインスタンス化し、アーティストをそのジャンルにも追加しようとしています。現在は動作していませんが、genre.artists を呼び出すと、空の配列が返されます。class Artist attr_accessor :name, :songs, :genres, :genre, :artists @@artists = []
def initialize(name = name, genre = genre)
@artists = []
@songs = []
@genre = genre
@genres = []
@name = name
@@artists << self
end
def self.all
@@artists
end
def self.reset_artists
@@artists = []
end
def self.count
self.all.size
end
def songs_count
self.songs.size
end
def count
self.size
end
def add_song(song)
@songs << song
@genres << song.genre
Genre.new(self)
end
end
class Genre
attr_accessor :name, :songs, :artists
@@genres = []
def initialize(artists = artists)
@songs = []
@artists = artists
@name = name
@@genres << self
end
def count
self.artists.count
end
def self.all
@@genres
end
def self.reset_genres
@@genre = []
end
end
class Song
attr_accessor :name, :genre, :artist
def initialize(name = name, artist = artist, genre = genre)
@name = name
@artist = artist
@genre = genre
end
end