2

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
rampion
  • 87,131
  • 49
  • 199
  • 315

4 Answers4

1

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

Ana Betts
  • 73,868
  • 16
  • 141
  • 209
  • Thanks - I had looked at highline but it seems to have some external dependencies and one of my constraints is that this has to work under Windows and Linux in both ruby and jruby. –  Dec 02 '08 at 03:33
1

I tried your code (under Windows) and it seemed to work fine. What OS are you using?

The Dark
  • 134
  • 1
0

I also tried your code (under OSX) with ruby 1.8.6 and it worked fine:

:! ruby prompt.rb
Prompt>(sdfsdf)

sdfsdf
Prompt>(default)

default

What do you get when you run the following?

c = gets
b = gets
a = gets
p [ a, b, c ]

I just hit 'Enter' 3x and get

["\n", "\n", "\n"]

I'm guessing what's wrong is that you're entering an infinite loop in your while statement by not passing it a defaultResponse (in some code that you're actually runinng that's not in your example).

rampion
  • 87,131
  • 49
  • 199
  • 315
0

I have confirmed (by running the program outside of Komodo) that the problem is in fact solely happening inside Komodo. I thank everyone for the feedback and taking the time to do the independent test (which I hadn't though of) to help narrow down the problem.

  • FYI - your responses should be comments to various answers, rather than answers themselves. Just a tip :) – rampion Dec 02 '08 at 19:05