【问题标题】:Printing something at the end of a gets input in ruby在 ruby​​ 的末尾打印一些内容
【发布时间】:2021-03-16 18:15:30
【问题描述】:

在 Ruby 中,如何在同一行中添加显示在用户 gets 输入末尾的内容?

类似这样的:

puts "What is your favorite quote? Please write below:"
print "\""
gets.strip
print "\"" # idealy displaying on the same line as gets
puts "great!"

但是在终端中有这个输出:

What is your favorite quote? Please write below:
"xyz quote"
great!

【问题讨论】:

  • 这有点困难,因为换行符用于完成gets ...
  • "My dog #{gets.chomp} likes other dogs" 在我输入"Saffi" 时显示My dog Saffi likes other dogs。你是这个意思吗?
  • @CarySwoveland 不是真的,如果一个字符可以跟随在同一行的输入之后,而不是在下面的一行打印输入,那就太好了
  • 您可能需要 Readline 或 HighLine,并且必须将 ”” 填充到输入缓冲区并将光标移动到引号之间。我真诚地怀疑这是否值得麻烦,并且不会处理各种边缘情况,但那将是一种潜在的方法。

标签: ruby printing terminal line


【解决方案1】:

require 'io/console' 获得对输入的细粒度控制。例如在STDIN.noecho { ... } 块内,您可以防止返回键在终端中打印新行。但是,它也会阻止打印所有其他字符,这可能会造成混淆。但是您可以使用STDIN.getch 逐个字符而不是逐行获取输入,并手动回显您想要显示的字符。诀窍是处理不可打印的键,例如退格键或 ctrl,您需要手动编程才能对输入执行正确的操作。

要正确实现您想要的行为,需要大量的工作。仔细考虑是否真的值得。

【讨论】:

  • 你好,马克斯。 LTNS。
【解决方案2】:

[H]如何在同一行添加显示在用户获取输入末尾的内容?

不要将您的输入与您想要表示输出的方式混为一谈。以不同的方式对待它们要容易得多。首先,检索用户的输入。其次,按照您想要的方式清理和格式化输出。

下面的类足够灵活,它不会关心用户的输入是否被引用;它也不关心输入行是否包含转义的双引号。

class Quote
  def initialize
    get_quote
    quote_the_quote
  end

  # get quote from user and adjust quotes on input
  def get_quote
    print 'What is your favorite quote? '

    # remove starting/ending double-quotes, remove escapes, and
    # convert internal double-quotes to single-quotes
    @quote = gets.chomp.gsub(/\A"|"\z/, '').delete('\\').tr(?", ?')
  end

  def quote_the_quote
    @quote = ?" + @quote + ?"
  end

  def print_quote
    puts "Selected quote: #{@quote}"
  end
end

Quote.new.print_quote

您的交互将如下所示:

What is your favorite quote? 'Twas brillig and the slithy toves...
Selected quote: "'Twas brillig and the slithy toves..."

因此,您不会在输入行中添加引号(如果用户直接添加引号,这可能会出现问题),但您当然可以将它们存储在 @quote 变量中,或在打印报价时将它们打印在标准输出上。将您的输入与输出区分开来还可以让您使用更复杂的输入做正确的事℠,例如:

  • This is "complicated."
  • "foo "bar" baz"
  • "quux \"wibble\" wobble"

肯定会出现边缘情况,因此您可能需要根据您的预期输入进行额外的更改。不过,这绝对可以帮助您入门!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多