Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gets function won't accept empty line more than once

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

1 Answers

This isn't technically an answer, but it'll help you anyways: use Highline (http://highline.rubyforge.org/), it'll save you a lot of grief if you're making a command-line interactive interface like this

like image 120
Ana Betts Avatar answered May 15 '26 15:05

Ana Betts