简体   繁体   English

gets.chomp没有移动到新的行

[英]gets.chomp without moving to a new line

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 ? 我理解在putsgets结束时自动完成的,以及如何处理这些,但有没有办法保持显示点(“光标位置”,如果你愿意)从移动到新线击中输入输入与后gets

eg 例如

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? 你好,我叫Jeremiah,你叫什么名字?

You can do this by using the (very poorly documented) getch : 你可以通过使用(记录很少的) 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 enter&IOError:字符缓冲IO的字节读取

Perhaps I'm missing something, but 'gets.chomp' works just fine does it not? 也许我错过了一些东西,但'gets.chomp'工作得很好不是吗? 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) (编辑:在TextMate中工作,而不是终端)

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM