Originally published 2008-09-03 at 13:16 CST Revised as module 2017-04-07

Hints for use:

name = 'Please enter your name -> '.prompt

I know that each time I want to ask a user for something, I need to write a way to ensure that the user sees the prompt, so that an appropriate answer can be provided. It makes sense to provide a method to do this, as it seems to be a pretty routine thing.

I do this by including a module Promptable with method prompt into String. It is easy to use, and ensures that stdout is flushed so that the user will get the question. If you find it useful, feel free to use it!

Maybe the method will be included some day as a core feature!

module Promptable
  def prompt
    print self
    STDOUT.flush unless STDOUT.sync
    gets
  end
end
String.include(Promptable)

We can now use Refinements for this as well… But that isn’t shown here.