实例化和集合-ruby

实例化和集合-ruby,ruby,Ruby,我是一个新手,正在努力通过考试。我有三门课,艺术家,歌曲和流派。我试图通过的测试如下: 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.ar

我是一个新手,正在努力通过考试。我有三门课,艺术家,歌曲和流派。我试图通过的测试如下:

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
这是我的艺术家课程,添加歌曲的方法是我需要调整的方法。当一首歌被添加到一个艺术家时,我试图实例化一个新的流派对象,并将艺术家添加到该流派中。但当前不工作,当我调用genre.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
def初始化(name=name,genre=genre)
@艺术家=[]
@歌曲=[]
@流派
@类型=[]
@name=name

@@艺术家创建新艺术家时,将其添加到
artist::artists
——一个
artist
的类变量。您测试的数组是
genre.artists
——一个
genre
的对象变量。这是与
Artist::artists
不同的变量,我没有看到您在代码中的任何地方更新
流派。artists
我很惊讶它甚至是一个数组,看到您没有将其初始化为数组…

您正在返回一个在
add\u song
方法中使用当前艺术家创建流派的新实例。你可以通过几种方式让你的考试通过

这将向歌曲实例中引用的流派添加艺术家

def add_song(song)
  @songs << song
  @genres << song.genre
  song.genre.artists << self
end

感谢Austin,当我尝试添加song.genre时,很抱歉我忘记将
.artists
添加到方法调用中。您希望将self引用的当前艺术家添加到流派中的艺术家数组中。
test 'A genre has many artists' do
  genre = Genre.new.tap{|g| g.name = 'rap'}

 [1,2].each do
   art ist = Artist.new
   song = Song.new
   song.genre = genre
   genre = artist.add_song(song)
 end 

 assert_equal genre.artists.count, 2
end