Ruby文本音乐播放器报错:nil无法隐式转换为字符串(TypeError)
Let's break down why you're hitting this TypeError first: when you run puts ' Genre is ' + album.genre, the album.genre value is nil. This happens because your read_genre() function isn't returning a valid genre value—Ruby defaults to returning nil when a function has no explicit return statement, which is exactly what's happening here.
Diagnosing the read_genre() Issues
Your original read_genre() has two critical flaws:
- No explicit return value: The function runs through its logic but never sends back the selected genre, leaving
album_genreasnil. - Broken, redundant loop logic: The
whileloop doesn't increment theindexvariable correctly, and the longcasestatement only prints genres instead of capturing them for return.
Fixed read_genre() Function
Let's rewrite this to be cleaner, maintainable, and actually return the selected genre:
$genre_names = ['Null','Pop', 'Classic', 'Jazz', 'Rock', 'KPop', 'Metal', 'Punk', 'Romance', 'Latin'] # Display the genre names in a numbered list and ask the user to select one def read_genre() # First, print all available genres clearly for the user puts "Available Genres:" $genre_names.each_with_index do |genre, idx| puts "#{idx}. #{genre}" end # Loop until the user enters a valid number in range loop do selected_num = read_integer_in_range("Select Genre: ", 0, 9) # Return the matching genre name once valid input is received return $genre_names[selected_num] if (0..9).cover?(selected_num) puts "Please select a valid number between 0 and 9!" end end
This version:
- Uses
each_with_indexto auto-print all genres (no more repetitivecasebranches) - Uses a
loopto force valid input before proceeding - Explicitly returns the selected genre string, so
album_genrewill never benil
Fix the read_album() Function Too
You also have a bug in read_album(): tracks = [tracks] references an undefined variable. Initialize it as an empty array instead:
def read_album album_title = read_string("Enter Title: ") album_artist = read_string("Enter Artist name: ") album_genre = read_genre() tracks = [] # Initialize empty track array (you can add tracks later) album = Album.new(album_title, album_artist, album_genre, tracks) album end
Why This Fixes the Error
Now when you call print_album(), album.genre will hold a valid string from $genre_names (like "Pop" or "Jazz") instead of nil, so concatenating it with ' Genre is ' will work without throwing a TypeError.
内容的提问来源于stack exchange,提问作者Elham Najeebullah

