The Accidental Rubyist

invalid byte sequence in UTF-8

User friendly command-line input with ruby readline

leave a comment »

While getting user input for various fields, you’d like some values to appear so the user can choose them via arrow keys, or Control-R. Readline makes this very simple.

Readline::HISTORY.push(*values) unless values.empty?

Readline::HISTORY is like an array. You can clear it, push values to it, print it using “to_a”.

To get user input, instead of “gets” we can use:

str = Readline::readline('>', boolean)

If boolean is true, entries will be automatically pushed into HISTORY.

When a user enters multiple records, its easy to save entries in a file based on column name, and add them to HISTORY before prompting him. So the user gets column-specific history. I am doing this in bugzyrb (a command-line bug tracker). Its on github in a file named cmdapp.rb history_read and history_save.

I might mention that Highline, also allows a readline flag in ask and question. However, from what I tried, it does not push valid values into HISTORY. It defines a completion_proc so you can tab complete the given options.

Advertisements

Written by totalrecall

July 10, 2010 at 8:32 pm

Posted in ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: