gets.chomp without moving to a new line

2019-02-15 09:19发布

问题:

I understand about the \n that's automatically at the end of puts and gets, and how to deal with those, but is there a way to keep the display point (the 'cursor position', if you will) from moving to a new line after hitting enter for input with gets ?

e.g.

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

would end up looking like

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

回答1:

You can do this by using the (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

References:

  • http://ruby-doc.org/stdlib-2.1.0/libdoc/io/console/rdoc/IO.html#method-i-getch
  • http://ruby-doc.org/stdlib-2.1.0/libdoc/io/wait/rdoc/IO.html#method-i-ready-3F

Related follow-up question:

enter & IOError: byte oriented read for character buffered IO



回答2:

Perhaps I'm missing something, but 'gets.chomp' works just fine does it not? To do what you want, you have to escape the apostrophe or use double-quotes, and you need to include what the user enters in the string that gets printed:

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

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

Works for me. (Edit: Works in TextMate, not Terminal)

Otherwise, you could just do something like this, but I realise it's not quite what you were asking for:

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