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