【问题标题】:gets.chomp without moving to a new linegets.chomp 不移动到新行
【发布时间】:2014-02-02 03:32:44
【问题描述】:

我了解 putsgets 末尾自动出现的 \n,以及如何处理这些问题,但有没有办法保持显示点(“光标位置”,如果你愿意的话) 在使用gets 输入输入后从移动到新行?

例如

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

最终会看起来像

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

【问题讨论】:

    标签: ruby newline gets


    【解决方案1】:

    您可以使用(记录非常差的)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
    

    参考资料:

    相关后续问题:

    enter & IOError: byte oriented read for character buffered IO

    【讨论】:

    • 这仅适用于 Ruby 2.1 吗?我有时会收到IOError: byte oriented read for character buffered IO,我不确定是不是因为我使用的是 Ruby 1.9.3。
    • 我从未尝试过 2.0 之前的功能,但如果 1.9.3 可以通过的话,它们至少部分存在。不过,我不知道它们当时的功能如何。
    • 你知道...很多...我喜欢这个 :) 但我知道的很少:(
    • 我在 1.9.3 和 2.0 中尝试过这个,我认为这个错误不是因为我使用的版本而显示的。在这里:stackoverflow.com/questions/21456829/… 我已经创建了主题。如果你有话要说,请说。谢谢。
    【解决方案2】:

    也许我遗漏了一些东西,但“gets.chomp”工作得很好,不是吗?要执行您想要的操作,您必须转义撇号或使用双引号,并且您需要在打印的字符串中包含用户输入的内容:

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

    为我工作。 (编辑:在 TextMate 中工作,而不是终端)

    否则,您可以这样做,但我意识到这并不是您所要求的:

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

    【讨论】:

    • 使用你的代码,我得到了两行的输出,第二行(Ruby 2.1)的开头重复了名称。
    • 我直接在 TextMate 中测试它,它的行为如你所愿。但是,是的,如果我在终端中运行它,我就会明白你的意思。有什么原因你不能先得到用户输入,然后只在一行上打印?
    • 我玩弄了gets的额外参数,似乎不支持。 Ctrl+D 可能会起作用——我还没有尝试过那个
    猜你喜欢
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2016-10-16
    • 2022-11-03
    • 2017-11-06
    相关资源
    最近更新 更多