在read_genre函数中,该函数在列表中显示可用的流派(我在函数外部的$ genre_name = []中定义了9种不同的流派),并提示用户使用case语句选择一个流派,然后读入用户输入号码的流派号码。从read_album函数调用read_genre函数,然后在print_album函数中打印输出。
问题在于,当我在终端中运行该程序时,提示我选择一种流派并输入数字,然后出现错误“从nil到整数(typeError)没有隐式转换。
我尝试通过将转换类型更改为to_i(int)仍然得到错误。
module Genre
POP, CLASSIC, JAZZ, ROCK, KPOP, METAL, PUNK, ROMANCE, LATIN = *1..9
end
$genre_names = ['Null','Pop', 'Classic', 'Jazz', 'Rock', 'KPop', 'Metal', 'Punk', 'Romance', 'Latin']
class Album
attr_accessor :title, :artist, :genre
def initialize (title, artist, genre)
@title = title
@artist = artist
@genre = genre
end
end
# 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
end
end
def read_album
album_title = read_string("Enter Title: ")
album_artist = read_string("Enter Artist name: ")
album_genre = read_genre()
album = Album.new(album_title, album_artist, album_genre)
album
end
def print_album album
puts ' Album information is: '
puts "Title is #{album.title}"
puts "Artist is #{album.artist}"
puts 'Genre is ' + album.genre.to_s
puts $genre_names[album.genre]
end
def read_integer_in_range(prompt, min, max)
value = read_integer(prompt)
while (value < min or value > max)
puts "Please enter a value between " + min.to_s + " and " + max.to_s + ": "
value = read_integer(prompt);
end
value
end
def main
puts "Welcome to the music player"
album = read_album()
print_album(album)
end
main
当我输入特定类型索引的编号时。例如,如果我输入2,它必须显示Classic,因为它在$ genre_names变量的索引2中。
答案 0 :(得分:0)
所以我认为您的read_integer(prompt)函数应该是这样的...
def read_integer(prompt)
print(prompt)
gets.strip().to_i
end
gets.strip()->这将返回一个字符串,例如。 “ 2”
“ 2” .to_i->然后将其从字符串转换为整数
这应该返回一个整数,然后您就可以参加比赛了。
希望这会有所帮助。