Buy @ Amazon

Convenience of Ruby's Readline

What API do you use to get input from terminal for a CLI app - use the combination of gets and chomp in ruby? That is okay. But didn't feel some pain trying to input again (and again?) in case of any input typo/error? Didn't you wish the CLI-app in ruby mimic the completion feature or the history feature as in the terminal?

Ruby's Readline comes to your rescue. Readline is a mudule in Ruby's standard library (stdlib). All you need to do to start using the Readline api is to require readline.

If earlier your earlier code looked something like below:
name = ""
until (name.length>0 and name.length<10)
  prompt = "Enter your name (length less than 10 characters): "
  print "#{prompt}"
  name = gets.chomp.strip
end

Using Readline's api the above code snippet would be as below:
require 'readline' #This goes in the beginning of the file
name = ""
until (name.length>0 and name.length<10)
  prompt = "Enter your name (length less than 10 characters): "
  name = Readline.readline(prompt, true) #true tells the API to add the user-input to the history.
end

Try both the code snippets above in your system. See if you can save some typing by pressing up/down arrows in both the cases. In the later case, you'll find it works just fine.

It pays to enrich your API knowledge of a language.. Happy learning!