Gets.chomp without a line break

I understand about \ n that is automatically at the end putsand gets, and how to deal with them, but is there a way to keep the displayed point ("cursor position", if you are) from going to a new line after pressing enter to enter with gets?

eg.

print 'Hello, my name is '
a = gets.chomp
print ', what your name?'

will look like

Hi, my name is Jeremiah, what's your name?

+3
source share
2 answers

You can do this using (very poorly documented) getch:

require 'io/console'
require 'io/wait'

loop do
  chars = STDIN.getch
  chars << STDIN.getch while STDIN.ready?       # Process multi-char paste
  break if ["\r", "\n", "\r\n"].include?(chars)
  STDOUT.print chars
end

Literature:

Relevant follow-up question:

IOError: IO

+7

, - , "get.chomp" , ? , , , , , :

    print 'Hello, my name is '
    a = gets.chomp
    print "#{a}, what your name?"

    # => Hello, my name is Jeremiah, what your name?

. (: TextMate, )

- , , , :

    puts "Enter name"
    a = gets.chomp
    puts "Hello, my name is #{a}, what your name?"
0

All Articles