Reputation: 150
I'm tinkering with a basic Tower of Hanoi game, and trying to get user input twice, but print both prompts on the same line (separated by the first input). I've searched for awhile, maybe I'm using the wrong terms. I assume the new line is due to gets, or setting it to a variable, but how do I get rid of it? Thanks!
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
I want this:
Move FROM which tower? (1 / 2 / 3) 1 ...TO which tower? (1 / 2 / 3) 2
But I'm getting this:
*Move FROM which tower? (1 / 2 / 3) 1
...TO which tower? (1 / 2 / 3) 2
(input in bold)
Upvotes: 2
Views: 2889
Reputation: 118261
Here is some other tricks using ANSI escape sequences
print "From Number "
num1 = gets.chomp.to_i
print "\033[1A\033[14C...TO Number "
num2 = gets.chomp.to_i
output
[arup@Ruby]$ ruby a.rb
From Number 1 ...TO Number 2
[arup@Ruby]$
Move the cursor up N lines: \033[NA
Move the cursor forward N columns: \033[NC
Values of N
you must need to be calculated as per the need. Cursor Movement.
Upvotes: 1
Reputation: 42182
In windows this does the thing
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
gives
#Move FROM which tower? (1 / 2 / 3) 1...TO which tower? (1 / 2 / 3) 2
#12
Upvotes: 1
Reputation: 19789
The reason you get a new line even after chomp
is because in the terminal you've already entered the carriage return key which displays the new line.
What you want can be done like this:
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})"
Note this will give an output of this:
$ ruby tower.rb
Move FROM which tower? (1 / 2 / 3) 1...TO which tower? (1 / 2 / 3) 2
Result: (1, 2)
Note this only gets one character from STDIN
.
Upvotes: 3