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

In Ruby, how can I print my next prompt on the same line after 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

我想要这个:

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

但我明白了:

*Move FROM which tower? (1 / 2 / 3) 1

...TO which tower? (1 / 2 / 3) 2

(输入粗体)

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

你想要的可以这样实现:

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.

中获取一个字符

在 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

这里有一些使用 ANSI escape sequences

的其他技巧
print "From Number "
num1 = gets.chomp.to_i
print "3[1A3[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.