2012-10-24 43 views
2

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

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

你已经试过了什么?你的代码是什么样的? – dpassage

+0

打印“标题?” title = STDIN.gets.chomp – Kivylius

回答

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]: 
相关问题