ib94
ib94

Reputation: 11

Printing out array gives strange output

I have an array tracks that is within another array known as albums. I have the following code which allows the user to enter the albums[index] and if it exists, allows the user to enter the tracks[index]. If that exists too, the album and track present at those indices are printed out.

However, when I run the code, instead of getting the album name and track name, I get the following output:

The selected track is The selected track is #<Track:0x2fca360> #<Album:0x2fca960>

Here's the relevant code snippets:

def play_selected_track(albums,tracks)
  # ask user to enter ID number of an album in the albums-list

  puts "Enter album id:"
  album_id = gets.chomp
  index = 0

  while (index<albums.length)
    if (album_id=="#{index}")
      puts "Please enter track id:"
      track_id = gets.chomp
      j = 0
      while (j<tracks.length)

        if (track_id == "#{j}")
          puts "The selected track is " + tracks[j].to_s + " " + albums[index].to_s
        end
        j += 1
      end 
    end 
    index += 1
  end 
end 
def main
  # fix the following two lines
  music_file = File.new("albums.txt", "r")
  albums = read_albums_file(music_file)
  tracks = read_tracks(music_file)
  print_albums(albums)
  music_file.close()
  play_selected_track(albums,tracks)
end

Upvotes: 0

Views: 56

Answers (1)

Yakov
Yakov

Reputation: 3191

By default #to_s returns the name of the object's class and the object id https://apidock.com/ruby/Object/to_s

If you implement your own #to_s method for Tack and Album then you get the proper results.

class Track
  def to_s
    name
  end
end

class Album
  def to_s
    name
  end
end

Better is to call #name explicitly. puts "The selected track is " + tracks[j].name + " " + albums[index].name

Upvotes: 1

Related Questions