Ruby irb Command History

If you spend any amount of time working with Ruby in the interactive shell (irb), what follows is a handy script for adding command completion support as well as command history across irb sessions.

require 'irb/completion'
require 'irb/ext/save-history'

ARGV.concat [ "--readline",
              "--prompt-mode",
              "simple" ]

# 25 entries in the list
IRB.conf[:SAVE_HISTORY] = 25

# Store results in home directory with specified file name
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"

The reference to SAVE_HISTORY is how many commands you want to store in the history list and the HISTORY_FILE is the name of the file where the commands are stored. Save the file as ~/.irbrc (in your home directory with the name .irbrc).

Below Ive enter several commands using irb. I used command completion (hitting tab key twice) on the line that begins with a.p and you can see how command completion shows the available options (a.pack, a.parition, etc).

Once I quite the irb session and open the .irb_history file it will look as follows:

Now, if I start a new irb session the commands in the history file be available by pressing the up arrow (not unlike the history available in a Terminal window). Although this configuration option is nothing new for those who been working with Ruby, it warrants mentioning for anyone who is just getting started with Ruby.

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *