我想要一个简单的 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]: