If you spend any time in a terminal, whether bash or zsh, you’ll probably know that by default these shells keeps a history of the commands you’ve run. Hit the up and down arrow keys in a terminal window and you can scroll through your most recent commands, which is great when you want to re-run long or complicated commands from previous sessions. But did you know you can get the same behaviour in your IRB and Rails console sessions?
Enable your IRB History
Update: As of Ruby 2.7 IRB history is enabled by default so the following only applies if you are running older versions of Ruby
Our trusty friend the IRB console has the exact same feature, meaning it will keep a history of your commands and let you scroll back through and re-run them. It’s just that by default it’s disabled!
To enable the history for your IRB sessions (and by extension your Rails console
sessions), add the following to a
.irbrc file in your home directory:
# ~/.irbrc IRB.conf[:SAVE_HISTORY] = 1000
Where 1000 is the number of commands you’d like IRB to remember. Now, whenever you run an IRB session or a Rails console, IRB will record the commands you run and make them available to you in current and future sessions.
Searching your command history
You can also search back through the history by hitting
CTRL-r and typing a
portion of the command you’re looking for. If the command you see isn’t quite
CTRL-r again to see the next matching result until you find what
you’re looking for. Once you’ve found the command you’re after, hit return and
that command will be executed. Or hit
CTRL-c to exit the search and you’ll be
back at an empty IRB prompt.
Incidentally, this command history search will also work in your standard terminal sessions.
But Tekin, I already have a command history in my Ruby console sessions and I haven’t done anything!
Well that might be because you use RVM. RVM does a whole heap of stuff under the hood, including configuring IRB quite heavily by default. Personally I prefer a less intrusive Ruby version manager such as chruby.
Other snazzy IRB customisations
There are other interesting things you might consider enabling for your IRB console sessions, including Auto indentation, Autocompletion , or even a Custom prompt. Take a look at the documentation for IRB for those and more.
More articles on Ruby & Rails