Я написал следующий код для чтения из файла и распечатки вывода в терминале. Я получаю вывод, но вместо того, чтобы распечатать его один раз, например:
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
Я получаю результат дважды, например:
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
Есть идеи, почему это может быть?
Это мой код:
class Track
attr_accessor :name, :location
def initialize (name, location)
@name = name
@location = location
end
end
# Returns an array of tracks read from the given file
def read_tracks(a_file)
count = a_file.gets().to_i()
i=0
tracks = Array.new()
while (i<count)
track = read_track(a_file)
tracks << track
i+=1
end
return tracks
end
# reads in a single track from the given file.
def read_track(a_file)
track_name=a_file.gets.chomp
track_location = a_file.gets.chomp
track = Track.new(track_name, track_location)
track.name= track_name
track.location= track_location
return track
end
# Takes an array of tracks and prints them to the terminal
def print_tracks(tracks)
index = 0
while (index<tracks.length)
print_track tracks[index]
index+=1
end
end
# Takes a single track and prints it to the terminal
def print_track(track)
puts(track.name)
puts(track.location)
end
# Open the file and read in the tracks then print them
def main()
a_file = File.new("input.txt", "r") # open for reading
tracks=read_tracks(a_file)
print_tracks(tracks)
# Print all the tracks
print_tracks(tracks)
end
main()