I want a simple pre-defined input in ruby. What I mean is that I want something to be there by default so the user can edit or just simply press Enter to skip. I'm using STDIN.gets.chomp
.
not predifiend : "Please enter a title: "
predefined : "Please enter a title: Inception " // "Inception" is pre-defined input]
The following is a sub-optimal solution as the default answer is not cleared instantly as the user begins to type:
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
If you want such a thing I guess you have to use more advanced terminal features. I guess ncurses could do the job.
Another option would be to just display the default answer in brackets and simply put the prompt behind that. A lot of simple command line tools do such thing. This could look like this:
Please enter a title [Inception]: