我正在创建一个基于文本的音乐播放器程序。
在Read_genre((函数中显示可用类型的列表(我在rade_gerre((函数之外定义了9种不同类型的列表$,其中读取用户输入的类型编号。然后从read_album调用read_genre并在print_album函数中打印出来。
问题在于,我正在收到错误'nill不隐含转换为字符串(typeError('第134行,该行是从print_album((函数中添加的 Genre is ' + album.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()
length = $genre_names.length
index = 0
print $genre_names
while (index < length)
select_genre = read_integer_in_range("Select Genre: ", 0,9)
case select_genre
when 1
puts "#{index + 1} " + $genre_names[1]
break
when 2
puts "#{index + 2 } " + $genre_names[2]
break
when 3
puts "#{index + 3} " + $genre_names[3]
break
when 4
puts "#{index + 4} " + $genre_names[4]
break
when 5
puts "#{index + 5} " + $genre_names[5]
break
when 6
puts "#{index + 6} " + $genre_names[6]
break
when 7
puts "#{index + 7} " + $genre_names[7]
break
when 8
puts "#{index + 8} " + $genre_names[8]
break
when 9
puts "#{index + 9} " + $genre_names[9]
break
else
puts 'Please Select again'
break
end
index
end
end
def read_album
# Complete the missing code
album_title = read_string("Enter Title: ")
album_artist = read_string("Enter Artist name: ")
album_genre = read_genre()
tracks = [tracks]
album = Album.new(album_title, album_artist, album_genre, tracks)
album
end
def print_tracks tracks
# Complete the missing code
index = 0
while (index < tracks.length)
print_track(tracks[index])
index += 1
end
end
您在main
方法中定义了music_file
,但是您正在尝试在其他未定义的方法中访问它,因此错误。
让我们分析您的代码在做什么:
def search_for_track_name(tracks, search_string)
index = 0
count = music_file.gets()
# Trying to access a variable that is outside of the method's scope
# music_file doesn't exist here.
while (index < count)
if (tracks[index] == search_string)
return found_index = -1
# You are returning -1 if the condition is true, which means
# returning -1 when the string is found even though you want
# the exact opposite.
end
index += 1
end
found_index
# If the pointer gets here, it means that the if statement was never true
# therefore found_index was never defined
end
让我们解决以下问题:
def search_for_track_name(tracks, search_string)
index = 0
count = tracks.length
# will loop through the array's items
while (index < count)
if (tracks[index] == search_string)
return index
# will return index if found
end
index += 1
end
-1
# if the loop finishes and nothing is found, will return -1
end
,或者您可以使用 index
方法,该方法返回数组中元素的第一匹匹配的索引。
tracks.index(search_string)
https://ruby-doc.org/core-2.6.3/array.html#method-i-index