gets.chomp without moving to a new line

余生长醉 提交于 2019-11-30 18:50:51

问题


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?"


来源:https://stackoverflow.com/questions/21107364/gets-chomp-without-moving-to-a-new-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!