I'm trying to write a simple ruby function that can prompt the user for a value and if the user presses ENTER by itself, then a default value is used. In the following example, the first call to the Prompt function can be handled by pressing ENTER by itself and the default value will be used. However, the second time I call Prompt and press ENTER, nothing happens, and it turns out I have to press some other character before ENTER to return from the 'gets' call.
There must be some way to flush the input buffer to avoid this problem. Anyone know what to do?
Thanks,
David
def BlankString(aString)
return (aString == nil) ||
(aString.strip.length == 0)
end
#Display a message and accept the input
def Prompt(aMessage, defaultReponse = "")
found = false
result = ""
showDefault = BlankString(defaultReponse) ? "" : "(#{defaultReponse})"
while not found
puts "#{aMessage}#{showDefault}"
result = gets.chomp
result.strip!
found = result.length > 0
if !found
then if !BlankString(showDefault)
then
result = defaultReponse
found = true
end
end
end
return result
end
foo = Prompt("Prompt>", "sdfsdf")
puts foo
foo = Prompt("Prompt>", "default")
puts foo