gets.chomp无需移至新行 [英] gets.chomp without moving to a new line

查看:132
本文介绍了gets.chomp无需移至新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解在putsgets末尾自动出现的\ n以及如何处理它们,但是有一种方法可以保持显示点(光标位置",如果您愿意)从gets?

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 ?

例如

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

最终看起来像

你好,我叫耶利米,你叫什么名字?

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

推荐答案

您可以通过使用(记录很少的)getch来做到这一点:

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

参考文献:

  • 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

相关的后续问题:

输入& IOError:针对字符缓冲的IO的面向字节的读取

这篇关于gets.chomp无需移至新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆