Ruby input failed

43 Views Asked by At

here is my code. I've encountered the bug that said: test.rb:101:in <main>': undefined method location' for nil:NilClass (NoMethodError) although i've defined the method tracks above. I've tried to debug and got the result that nothing was pushed into the tracks variable. Please help me in this stage.

puts albums[0].tracks[0].location `

class Album
  attr_accessor :author, :name, :year, :genre, :cover, :count, :tracks
    def initialize (author, name, year, genre, cover, count, tracks)
        @author = author
        @name = name
        @year = year
        @genre = genre
        @cover = cover
        @count = count
        @tracks = tracks
    end
end
  
  
class Track
      attr_accessor :name, :location
      def initialize (name, location)
          @name = name
          @location = location
      end
end

def read_track(pineapple_music)
    song = pineapple_music.gets
    file = pineapple_music.gets
    t = Track.new(song, file)
    return t
end 
 
def read_tracks(pineapple_music, count)
    tracks = Array.new
    trackcount = count
    while trackcount < count
    track = read_track(pineapple_music)
    tracks << track 
    trackcount += 1 
    end
    return tracks
end


def read_album(music_file)
    album_author = music_file.gets.chomp
    album_name = music_file.gets.chomp
    album_year = music_file.gets.chomp.to_i
    album_genre = music_file.gets.chomp.to_i
    cover = music_file.gets.chomp
    count = music_file.gets.chomp.to_i
    tracks = read_tracks(music_file, count)  
    album = Album.new(album_author, album_name, album_year, album_genre, cover, count, tracks)
    return album
end

def read_albums(pineapple_music)  
    count = pineapple_music.gets.to_i
    albums = Array.new
    albumcount = 0
    while albumcount < count
    album = read_album(pineapple_music)
    albums << album
    albumcount += 1 
    end
    return albums
end
    
def read_file(pineapple_music)
      music_file = File.new(pineapple_music, "r")
      albums = read_albums(music_file)
      music_file.close()
      return albums
end

def read_number_albums(pineapple_music)
    music_file = File.new(pineapple_music, "r")
    count = music_file.gets.to_i
    music_file.close()
    return count
end

`

I've tried some methods like try to output in every function to see what happened. I'm expecting the file name in the library to be loaded in the program, but nothing was loaded and the output was nil afterall.

0

There are 0 best solutions below