Allowing Input Editing with Readline

Problem

You want to let your users edit their lines of input as they write them, the way irb does.

Solution

Use the readline library. Instead of reading directly from standard input, pass a prompt string into Readline.readline. The user will be able to edit their input using the same shortcut keys you can use in the irb Ruby interpreter (assuming their terminal supports those keys).

#!/usr/bin/ruby -w # readline.rb require eadline vegetable = Readline.readline("Whats your favorite vegetable?> ") puts "#{vegetable.capitalize}? Are you crazy?"

Note that you don have to chomp the result of Readline.readline:

$ ruby readline.rb Whats your favorite vegetable?> okra Okra? Are you crazy?

On Windows, this isn necessary because the cmd shell provides any console program with many of readlines features. The example given above will work on both Windows and Unix, but if you e writing a Windows-specific program, you don need readline:

# readline_windows.rb print "Whats your favorite vegetable?> " puts gets.chomp.capitalize + "? Are you crazy?"

Discussion

In a Unix program that accepts data from standard input, the user can use their backspace key to correct typing mistakes, one character at a time. Backspace is a control character: its a real character, just like "1" and "m" (its Ruby string representation is "10"), but its not usually interpreted as data. Instead, its treated as a command: it erases one character from the input buffer.

With the backspace key, you can correct errors one character at a time. But what if you want to insert text into the middle of a line, or delete the whole thing and start over? Thats where readline comes in. Its a Ruby interface to the Readline library used by many Unix programs, and it recognizes many control characters besides the backspace.

In a readline program, you can use the left and right arrow keys to move back and forth in the input string before submitting it. If you e familiar with the Readline shortcut keys from Emacs or other Unix programs, you can perform more sophisticated text editing operations, including cut and paste.

The readline library also supports command history: thats the feature of irb that lets you revisit commands youve already typed. To add this feature to your program, pass true as the second argument to Readline.readline. When the user enters a line, her input will be added to the command history. The next time your code calls Readline.readline, the user can hit the up arrow key to recall previous lines of input.

Heres a simple Ruby interpreter that has all the line- editing capabilities of irb, including command history:

#!/usr/bin/ruby -w # mini_irb.rb require eadline line = 0 loop do eval Readline.readline(\%.3d> % line, true) line += 1 end

See Also

Категории