Вопрос

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?

Это было полезно?

Решение

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:

Related follow-up question:

enter & IOError: byte oriented read for character buffered IO

Другие советы

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?"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top