def print_tracks(tracks)
index = 0
while (index<tracks.length)
print_track tracks[index]
index+=1
end
end
def print_track(track)
puts('Track title is: ’ + track.title)
puts('Track file location is: ’ + track.location)
end
def main()
a_file = File.new(“input.txt”, “r”) # open for reading
print_tracks(tracks)
end
main()
But I keep getting the following error: Traceback (most recent call last):
1: from track_file_handling.rb:68:in <main>' track_file_handling.rb:65:in main’: undefined local variable or method
`tracks’ for main:Object (NameError)
I am relatively new to ruby so I cannot figure out why this is happening. Any feedback on whether my code can actually do what I want it to will also be appreciated.
def main()
a_file = File.new(“input.txt”, “r”) # open for reading
print_tracks(tracks)
end
It first opens a file to read, and names it a_file.
Then it calls print_tracks passing it the value of variable tracks. But tracks is not defined, hence your error.
Hi pcl. Thank you for your reply. I was able to get my code running thanks to your suggestion. However, it now printing out the output twice instead of once. For example. it is printing out:
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
instead of just:
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
However, it now printing out the output twice instead of once.
I don’t see any reason - it looks like print_tracks is being called twice. Take a look at main and see where/how it is printing.
Incidentally:
in your read_track method, you don’t have to set the values for the track name and location - you have passed them to the constructor, and the initialize method stores them into fields. It is simpler to write:
def read_track(a_file)
track_name=a_file.gets.chomp
track_location = a_file.gets.chomp
return Track.new(track_name, track_location)
end
in print_track you first try to print track.title -> this should be track.name.
1 Like
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.