ruby - 如何设置预定义输入

标签 ruby stdin gets

我想要一个简单的 ruby​​ 预定义输入。我的意思是,我希望默认情况下有一些内容,以便用户可以编辑或只需按 Enter 即可跳过。我正在使用STDIN.gets.chomp .

not predifiend : "Please enter a title: "
predefined : "Please enter a title: Inception " // "Inception" is pre-defined input]

最佳答案

以下是次优解决方案,因为当用户开始键入时,默认答案不会立即清除:

prompt = 'Please enter a title: '
default_answer = 'Inception'

# Print the whole line and go back to line start
print "#{prompt}#{default_answer}\r"
# Print only the prompt so that the cursor stands behing the prompt again
print prompt

# Fetch the raw input
input = gets

# If user just hits enter only the linebreak is put in
if input == "\n"
  answer = default_answer
else # Otherwise the typed string including a linebreak is put in
  answer = input.chomp
end

puts answer.inspect

如果你想要这样的东西,我想你必须使用更高级的终端功能。我想 ncurses 可以完成这项工作。

另一种选择是仅在括号中显示默认答案,然后将提示放在其后面。很多简单的命令行工具都可以做这样的事情。这可能看起来像这样:

 Please enter a title [Inception]:

关于ruby - 如何设置预定义输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053093/

相关文章:

ruby-on-rails - 生成一个唯一且随机的 6 个字符长的字符串来表示 ruby​​ 中的链接

bash - 需要对 kubectl stdin 和 pipeline 进行一些解释

c - 为什么我在使用字符串数组、gets 和 puts 的 for 循环中得到垃圾?

c - 在此代码中除了使用 gets(c) 和 gets(s) 之外,还有什么替代方案?

go - TCP 将 Stdout 发送到客户端并从客户端读取 Stdin

c - 如何使用 gets() 函数直接写入指针?

ruby-on-rails - 无法打开 CSV 文件 : no implicit conversion of StringIO into String

ruby-on-rails - Rails - 如何从 S3 获取图像、调整图像大小并将缩略图保存到 S3?

android - Android 上的 Ruby 处理

go - 键盘或管道文件输入