红宝石铅。用" STDIN.getc"和""循环

时间:2016-06-27 14:53:49

标签: ruby

我在使用以下代码时遇到了一些问题:

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'例如,有两个问题:

  • ""运行所有案例,不仅适用于'炭
  • WHILE循环中的STDIN.getc似乎被执行了2次,即使我只键入一次char。

错误在哪里?

1 个答案:

答案 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