如何设置预定义输入

时间:2012-10-24 16:04:07

标签: 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]

1 个答案:

答案 0 :(得分:3)

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

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]: