在Ruby中,如何在用户输入后在同一行上打印下一个提示?

时间:2015-02-24 19:18:13

标签: ruby user-input

我正在修补一个基本的河内塔游戏,并试图让用户输入两次,但在同一行上打印两个提示(由第一个输入分隔)。我搜索了一段时间,也许我使用了错误的条款。我假设新行是由于获取,或将其设置为变量,但我该如何摆脱它?谢谢!

print "Move FROM which tower? (1 / 2 / 3) "
answer1 = gets.chomp.to_i
print "...TO which tower? (1 / 2 / 3) "
answer2 = gets.chomp.to_i

我想要这个:

  

从哪个塔移动? (1/2/3) 1 ......哪个塔? (1/2/3) 2

但我得到了这个:

  

*从哪个塔移动? (1/2/3) 1

     

......哪个塔? (1/2/3) 2

(以粗体输入)

3 个答案:

答案 0 :(得分:3)

即使在chomp之后您获得新行的原因是因为在终端中您已经输入了显示新行的回车键。

你想要的是这样的:

require "io/console"
print "Move FROM which tower? (1 / 2 / 3) "
x = STDIN.getch.to_i
print x
print "...TO which tower? (1 / 2 / 3) "
y = STDIN.getch.to_i
print "#{y}\n"
print "Result: (#{x}, #{y})"

注意这将给出一个输出:

$ ruby tower.rb
Move FROM which tower? (1 / 2 / 3) 1...TO which tower? (1 / 2 / 3) 2
Result: (1, 2)

注意这只会从STDIN获得一个字符。

答案 1 :(得分:1)

在Windows中,这就是事情

require "Win32API"

def read_char
  Win32API.new("crtdll", "_getch", [], "L").Call
end

print "Move FROM which tower? (1 / 2 / 3) "
print answer1 = read_char.chr
print "...TO which tower? (1 / 2 / 3) "
puts answer2 = read_char.chr

puts answer1+answer2

给出

#Move FROM which tower? (1 / 2 / 3) 1...TO which tower? (1 / 2 / 3) 2
#12

答案 2 :(得分:1)

以下是使用ANSI escape sequences

的其他一些技巧
print "From Number "
num1 = gets.chomp.to_i
print "\033[1A\033[14C...TO Number "
num2 = gets.chomp.to_i

<强>输出

[arup@Ruby]$ ruby a.rb
From Number 1  ...TO Number 2
[arup@Ruby]$
  • 将光标向上移动N行: \ 033 [NA

  • 将光标向前移动N列: \ 033 [NC

N的值必须根据需要计算。 Cursor Movement