我在使用以下代码时遇到了一些问题:
puts "Press a key"
key = STDIN.getc
puts key.class
puts "You have pressed #{key}"
puts key.class
while key != "f" do
case key
when "g"
puts "It's 'g'"
when "h"
puts "It's 'h'"
when "j"
puts "It's 'j'"
else
puts "You gave me #{key} -- I have no idea what to do with that."
end
puts "Press a key"
key = STDIN.getc
puts "You have pressed #{key}"
end
如果您输入' f',它可以正常工作,但如果您输入' g'例如,有两个问题:
错误在哪里?
答案 0 :(得分:1)
不完全确切,但似乎STDIN.getc
不会阻止循环
你可以试试这样的东西
puts "Press a key"
while key = gets.chomp
break if key == "f"
puts key.class
puts "You have pressed #{key}"
puts key.class
case key
when "g"
puts "It's 'g'"
when "h"
puts "It's 'h'"
when "j"
puts "It's 'j'"
else
puts "You gave me #{key} -- I have no idea what to do with that."
end
puts "Press a key"
end