Modern IRB
suggest changeIf you last used IRB years ago, you may remember a bare prompt that couldn't edit multi-line input and had little to offer beyond evaluating expressions. Many people installed Pry to get more.
IRB has been rebuilt piece by piece since Ruby 2.7, and most of what Pry offered is now built in:
- Ruby 2.7: multi-line editing and syntax highlighting (via the Reline library)
- Ruby 3.0 and 3.1:
ls,show_source,whereami, and an autocompletion popup that shows documentation - Ruby 3.2:
editand debugger commands (debug,next,step,break) that hand over to the debug gem - Ruby 3.3: a pager for long output, and type-based completion (opt-in)
- Ruby 3.4: type-based completion on by default (
repl_type_completorbecame a bundled gem),historyandhelpreplacingshow_cmds, and a public API for your own commands - Ruby 4.0: IRB 1.16, now a bundled gem instead of a default gem, plus a
copycommand
This article covers everyday IRB use with Ruby 4.0.7 and IRB 1.16.0. For the basics see IRB, Basic Usage and Starting an IRB session inside a Ruby script.
To see what your IRB is using, run irb_info:
irb(main):001> irb_info
Ruby version: 4.0.7
IRB version: irb 1.16.0 (2025-12-17)
InputMethod: RelineInputMethod with Reline 0.6.3
Completion: Autocomplete, ReplTypeCompletor: 0.1.12, Prism: 1.8.1, RBS: 3.10.0
RUBY_PLATFORM: x64-mingw-ucrt
East Asian Ambiguous Width: 1
Code page: 852
irb_info output is a good thing to include in a bug report. The Completion: line says which completor is active, which is covered below.
Multi-line editing
IRB knows when an expression is incomplete. It indents continuation lines automatically, and while the expression is unfinished the prompt ends with * instead of >:
irb(main):001* def hi(name)
irb(main):002* "Hello, #{name}"
irb(main):003> end
=> :hi
irb(main):004> hi("Ruby")
=> "Hello, Ruby"
irb(main):005> _
=> "Hello, Ruby"
_ always holds the last result.
While you edit, the whole def ... end block is one buffer. You can move the cursor up into an earlier line and fix a typo before pressing Enter. Pressing the up arrow at the prompt recalls the whole block from history, not just its last line. Enter on an incomplete expression adds a new line. Enter on a complete one evaluates it.
Useful key bindings (Reline follows Readline's Emacs-style defaults):
| Key | Action |
|---|---|
| Up / Down | Previous / next history entry (a multi-line entry comes back whole) |
| Ctrl+R | Incremental search through history |
| Tab | Complete, or cycle through the completion popup |
| Ctrl+A / Ctrl+E | Start / end of line |
| Ctrl+U / Ctrl+K | Delete to start / end of line |
| Ctrl+D | Exit (on an empty line) |
Reline reads ~/.inputrc if you want Vi mode (set editing-mode vi) or different bindings.
Autocompletion and type-based completion
As you type, IRB shows a popup of candidates under the cursor. Tab cycles through them, and the documentation of the selected method (from ri) is shown next to the list. Turn the popup off with --noautocomplete or IRB.conf[:USE_AUTOCOMPLETE] = false. Tab completion keeps working without it.
IRB has two completion engines:
- RegexpCompletor, the classic one. It splits the input with regular expressions and evaluates only simple receivers such as local variables, constants and literals.
- TypeCompletor, from the
repl_type_completorgem. It parses the input with Prism and infers types using the RBS signatures of the core and standard library. It never calls your methods; it reads types from their signatures.
Ruby 3.4 and newer use the type completor by default when repl_type_completor is available. It ships as a bundled gem, so normally it is. Here is what each completor offers for the same input, with words = %w[apple banana] in scope:
| Input | RegexpCompletor | TypeCompletor |
|---|---|---|
words.first.up |
nothing | upcase, upcase!, upto |
words.map { it.up |
nothing | upcase, upcase!, upto |
words.to_h { [it, it.size] }.values.first.ev |
nothing | even? |
The regexp completor can't tell what words.first returns without calling it, and has no idea what it is inside a block. The type completor knows that Array[String]#first returns a String and that it in map is an element.
Choose an engine explicitly with a flag, an environment variable or a config setting:
$ irb --type-completor
$ irb --regexp-completor
$ IRB_COMPLETOR=regexp irb
# ~/.irbrc
IRB.conf[:COMPLETOR] = :regexp
If you ask for :type and the gem can't be loaded (for example inside a Bundler project whose Gemfile doesn't list repl_type_completor), IRB prints a warning and falls back to the regexp completor. On Ruby 3.3, install the gem and pass --type-completor to opt in.
Exploring objects: ls
ls lists the methods, constants, instance variables and locals visible on an object, grouped by where they are defined. Here is a small class we'll use in the following examples:
# shapes.rb
class Circle
attr_reader :radius
def initialize(radius)
@radius = radius
end
# Area of the circle.
def area
Math::PI * radius**2
end
def to_s = "Circle(#{radius})"
end
irb -r ./shapes requires the file before the first prompt:
irb(main):001> c = Circle.new(2)
=> #<Circle:0x000002d8ddc43598 @radius=2>
irb(main):002> ls c
Circle#methods: area radius to_s
instance variables: @radius
irb(main):003> ls Comparable
Comparable#methods: < <= == > >= between? clamp
irb(main):004> ls Math
constants: DomainError E PI
Math.methods:
acos acosh asin asinh atan atan2 atanh cbrt cos cosh erf
erfc exp expm1 frexp gamma hypot ldexp lgamma log log10 log1p
log2 sin sinh sqrt tan tanh
-g filters by a regular expression, which beats scrolling through "str".methods.sort:
irb(main):005> ls "str" -g ^up
String#methods: upcase upcase! upto
ls with no argument lists what's visible on the current self. The last line, locals:, is handy inside binding.irb.
Reading code: show_source, show_doc, edit
show_source (alias $) prints the definition of a method, class, module or constant, with its file and line:
irb(main):001> show_source Circle#area
From: /path/to/shapes.rb:9
def area
Math::PI * radius**2
end
irb(main):002> show_source c.to_s
From: /path/to/shapes.rb:13
def to_s = "Circle(#{radius})"
irb(main):003> $ Circle
From: /path/to/shapes.rb:1
class Circle
attr_reader :radius
def initialize(radius)
@radius = radius
end
# Area of the circle.
def area
Math::PI * radius**2
end
def to_s = "Circle(#{radius})"
end
The target can be Class#instance_method, Class.class_method, Mod::CONST, or an expression like c.to_s, which IRB evaluates to find the receiver. Add -s to show the super method (and -ss for the one above it). Here Ring < Circle overrides area:
irb(main):001> show_source Ring#area
From: /path/to/shapes2.rb:9
def area
super - Math::PI * @inner**2
end
irb(main):002> show_source Ring#area -s
From: /path/to/shapes.rb:9
def area
Math::PI * radius**2
end
Methods written in C have no Ruby source, so the result is Error: Couldn't locate a definition for Array#tally. For those, use show_doc, which shows the ri documentation:
irb(main):001> show_doc Array#tally
= Array#tally
(from ruby core)
=== Implementation from Enumerable
------------------------------------------------------------------------
tally(hash = {}) -> hash
------------------------------------------------------------------------
When argument hash is not given, returns a new hash whose keys are the
distinct elements in self; each integer value is the count of
occurrences of each element:
%w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}
...
edit Circle#area opens the file that defines the method in $VISUAL or $EDITOR (IRB prints the command and path first). It passes only the path, not the line number. edit with no argument opens the file of the current binding.irb. After you save, reload the file with load "./shapes.rb" or IRB's irb_load / source command.
History
IRB saves input history to ~/.irb_history (1000 entries by default) and loads it in the next session. The history command lists it, newest first, and -g filters it:
irb(main):001> data = JSON.parse('{"a": [1, 2, 3]}')
=> {"a" => [1, 2, 3]}
irb(main):002> data["a"].sum
=> 6
irb(main):003> data.keys
=> ["a"]
irb(main):004> history -g data
3: history -g data
2: data.keys
1: data["a"].sum
0: data = JSON.parse('{"a": [1, 2, 3]}')
-G does the same as -g. Entries longer than two lines are shortened with .... The history only exists when IRB reads from a terminal. When IRB's input is a pipe, history raises an error and nothing is saved.
Separate from input history, IRB can keep a numbered list of results. Set IRB.conf[:EVAL_HISTORY] = 5 (example below) and __ shows the last five results keyed by line number. __[8] returns the result of line 8.
Measuring and the pager
measure prints how long each evaluation takes until you turn it off:
irb(main):001> words = %w[apple banana cherry]
=> ["apple", "banana", "cherry"]
irb(main):002> measure
TIME is added.
irb(main):003> words.sort_by { -it.size }
processing time: 0.000123s
=> ["banana", "cherry", "apple"]
irb(main):004> measure :off
measure :stackprof uses the stackprof gem for a sampling profile when it is installed.
Output longer than the terminal (from ls, show_source, show_doc, help or a big return value) goes through a pager: $PAGER, then less, then more. Press q to return to the prompt. Disable it with irb --no-pager or IRB.conf[:USE_PAGER] = false. The pager is used only when IRB is attached to a terminal.
Changing context with cd
cd obj makes obj the current self, so you can call its methods without a receiver. cd .. goes back:
irb(main):001> words = %w[apple banana cherry]
=> ["apple", "banana", "cherry"]
irb(main):002> cd words
irb(["apple", "banana", "cherry"]):003> size
=> 3
irb(["apple", "banana", "cherry"]):004> first
=> "apple"
irb(["apple", "banana", "cherry"]):005> cd ..
irb(main):006> cd Circle
irb(Circle):007> cwws
Current workspace: Circle
The prompt shows the current object. cd replaced the older pushws/popws/chws commands, which still exist. The "multi-irb" commands (irb, jobs, fg, kill) are deprecated.
help
help lists every command by category, including your own commands (shown later). help <command> shows the details:
irb(main):001> help show_source
Usage: show_source [target] [-s]
-s Show the super method. You can stack it like `-ss` to show the super of the super, etc.
Examples:
show_source Foo
show_source Foo#bar
show_source Foo#bar -s
show_source Foo.baz
show_source Foo::BAR
Other commands worth knowing are whereami (alias @, reprints the code around a binding.irb), context (dumps the current settings) and copy [expr], which copies the inspected result to the clipboard. copy looks for pbcopy or xclip; on other systems set IRB.conf[:COPY_COMMAND], for example to "clip.exe" on Windows.
When a local variable has the same name as a command, the variable wins. Type ls with a local ls defined and you get the variable's value.
binding.irb
Put binding.irb anywhere in a program to stop there with a REPL that sees the local variables, self and instance variables at that point. No require is needed. IRB prints the surrounding code first:
# order.rb
Item = Struct.new(:name, :price, :qty)
def total(items, discount)
subtotal = items.sum { |i| i.price * i.qty }
binding.irb
subtotal - discount
end
items = [Item.new("pen", 3, 4), Item.new("pad", 5, 2)]
puts "total: #{total(items, 2)}"
$ ruby order.rb
From: order.rb @ line 5 :
1: Item = Struct.new(:name, :price, :qty)
2:
3: def total(items, discount)
4: subtotal = items.sum { |i| i.price * i.qty }
=> 5: binding.irb
6: subtotal - discount
7: end
8:
9: items = [Item.new("pen", 3, 4), Item.new("pad", 5, 2)]
10: puts "total: #{total(items, 2)}"
irb(main):001> subtotal
=> 22
irb(main):002> items.map(&:name)
=> ["pen", "pad"]
irb(main):003> discount = 10
=> 10
irb(main):004> exit
total: 12
Assignments stick: setting discount in the session changed the program's result from 20 to 12. exit resumes the program. exit! ends the whole process.
A binding.irb inside a loop stops on every iteration. disable_irb resumes and turns off all further binding.irb calls for the rest of the run:
# loop.rb
3.times do |i|
binding.irb
puts "iteration #{i} done"
end
puts "finished"
irb(main):001> i
=> 0
irb(main):002> exit
iteration 0 done
From: loop.rb @ line 2 :
...
irb(main):001> i
=> 1
irb(main):002> disable_irb
iteration 1 done
iteration 2 done
finished
Debugger integration
From a binding.irb session you can switch to the debug gem without restarting. The debug, next, step, continue, finish, break, catch, delete, backtrace and info commands load the debugger and run the matching debugger command. After that, the prompt changes to irb:rdbg, and both debugger commands and Ruby expressions work at it:
irb(main):001> subtotal
=> 22
irb(main):002> next
(rdbg:irb) next
[1, 10] in order.rb
1| Item = Struct.new(:name, :price, :qty)
2|
3| def total(items, discount)
4| subtotal = items.sum { |i| i.price * i.qty }
5| binding.irb
=> 6| subtotal - discount
7| end
8|
9| items = [Item.new("pen", 3, 4), Item.new("pad", 5, 2)]
10| puts "total: #{total(items, 2)}"
=>#0 Object#total(items=[#<struct Item name="pen", price=3, qty=..., discount=2) at order.rb:6
#1 <main> at order.rb:10
irb:rdbg(main):003> subtotal - discount
20
irb:rdbg(main):004> info locals
%self = main
items = [#<struct Item name="pen", price=3, qty=4>, #<struct Item name="pad", price=5, qty=2>]
discount = 2
subtotal = 22
irb:rdbg(main):005> continue
total: 20
(The debugger output above was produced with RUBY_DEBUG_NO_COLOR=1. By default it's colored.)
This lets you start with binding.irb, which needs no setup, and switch to stepping only when you need it. The reverse direction also works: in an rdbg session the irb command opens IRB at the current frame, and RUBY_DEBUG_IRB_CONSOLE=1 makes IRB the debugger's console. Breakpoints, catchpoints, tracing and remote debugging are covered in the companion article "Debugging with the debug gem" in the Debugging chapter. Pry users should also read Stepping through code with Pry and Byebug.
Configuring IRB: .irbrc
IRB loads Ruby configuration files at startup. It checks $IRBRC, $XDG_CONFIG_HOME/irb/irbrc, ~/.irbrc and ~/.config/irb/irbrc (the last one only when XDG_CONFIG_HOME isn't set), then .irbrc in the current directory, and loads every one of them that exists, in that order. A personal file in your home directory and a project file can therefore both apply. irb -f skips them all.
A personal config with history settings, a custom prompt, an alias and a custom command:
# ~/.irbrc
IRB.conf[:SAVE_HISTORY] = 10_000
IRB.conf[:HISTORY_FILE] = File.expand_path(".irb_history_custom", Dir.home)
IRB.conf[:EVAL_HISTORY] = 5
IRB.conf[:PROMPT][:SHORT] = {
PROMPT_I: "%m> ", # normal prompt
PROMPT_S: "%m%l ", # inside a string literal
PROMPT_C: "%m* ", # continued statement
RETURN: "#=> %s\n"
}
IRB.conf[:PROMPT_MODE] = :SHORT
IRB.conf[:COMMAND_ALIASES][:ss] = :show_source
class TimeCommand < IRB::Command::Base
category "Misc"
description "Show the current time."
help_message "Usage: now [strftime format]"
def execute(arg)
fmt = arg.empty? ? "%H:%M:%S" : arg
puts Time.now.strftime(fmt)
end
end
IRB::Command.register(:now, TimeCommand)
In prompt strings, %m is self, %n the line number (%03n zero-padded), %N the program name and %l the open string delimiter. Built-in modes are :DEFAULT, :CLASSIC, :SIMPLE, :INF_RUBY, :XMP and :NULL.
A command receives everything after its name as one string (arg) and is not evaluated as Ruby. A helper method is the other kind of extension: a real method call that takes Ruby arguments and returns a value. A project .irbrc is a good place for helpers that load the app and build test data:
# .irbrc in the project directory
require_relative "shapes"
class CirclesHelper < IRB::HelperMethod::Base
description "Build sample circles with radius 1..n."
def execute(n = 3) = (1..n).map { Circle.new(it) }
end
IRB::HelperMethod.register(:circles, CirclesHelper)
Starting irb in that directory picks up both files:
main> "multi
main" line"
#=> "multi\nline"
main> [1,
main* 2].sum
#=> 3
main> ss Circle#to_s
From: /path/to/shapes.rb:13
def to_s = "Circle(#{radius})"
main> now %Y-%m-%d
2026-10-18
main> help now
Usage: now [strftime format]
main> circles(2)
#=> [#<Circle:0x000002424f408510 @radius=1>, #<Circle:0x000002424f4084c0 @radius=2>]
main> _.map(&:area)
#=> [3.141592653589793, 12.566370614359172]
main> __
#=>
1 "multi\nline"
3 3
8 [#<Circle:0x000002424f408510 @radius=1>, #<Circle:0x000002424f4084c0 @radius=2>]
9 [3.141592653589793, 12.566370614359172]
main> __[8].size
#=> 2
The " in the second prompt is %l, showing that a string literal is still open. Commands (ss, now, help) don't produce results, so they don't appear in __. help lists now under "Misc", circles under "Helper methods" and ss under "Aliases".
If a config file raises an error, IRB prints Error loading RC file '...' with the backtrace and starts anyway. Other useful settings:
| Setting | Effect |
|---|---|
IRB.conf[:USE_AUTOCOMPLETE] = false |
No popup; Tab completion still works |
IRB.conf[:COMPLETOR] = :regexp |
Use the classic completor |
IRB.conf[:USE_PAGER] = false |
Never page output |
IRB.conf[:USE_COLORIZE] = false |
No syntax highlighting |
IRB.conf[:SAVE_HISTORY] = nil |
Don't save history |
IRB.conf[:ECHO_ON_ASSIGNMENT] = false |
Don't print the value of x = ... (default: truncated to one line) |
IRB.conf[:INSPECT_MODE] = :pp |
How results are printed (:pp is the default; also :inspect, :to_s, :yaml, :marshal) |
IRB.conf[:BACK_TRACE_LIMIT] = 30 |
Lines of backtrace shown for errors |
IRB in projects (Ruby 4.0)
In Ruby 4.0, irb and reline are bundled gems instead of default gems. Outside Bundler nothing changes, since bundled gems are installed with Ruby. But bundle exec irb, and binding.irb in a program run with bundle exec, can only load gems listed in the lockfile. Add IRB to the development group:
# Gemfile
group :development, :test do
gem "irb"
gem "repl_type_completor" # type-based completion under Bundler
gem "debug" # debug/next/step from binding.irb
end
Without gem "irb", Ruby 3.4 already warns that irb will no longer be part of the default gems. On Ruby 4.0 the require fails.
Non-interactive use
IRB also reads from a pipe, which is handy for quick checks in scripts. It echoes each input line and prints results without =>. Add --prompt default to get the usual transcript format:
$ printf '1 + 2\n[3, 1, 2].sort\n' | irb -f --nocolorize --prompt default
Switch to inspect mode.
irb(main):001> 1 + 2
=> 3
irb(main):002> [3, 1, 2].sort
=> [1, 2, 3]
irb(main):003>
In this mode there is no Reline: no completion, history or pager, and history raises an error. Use ruby -e when you only need the output.
Summary
| Task | Command |
|---|---|
| List methods/variables | ls obj, ls obj -g pattern |
| Show source | show_source Foo#bar, $ Foo, -s for super |
| Show docs | show_doc Array#tally |
| Open in editor | edit Foo#bar |
| Search past input | history -g pattern, Ctrl+R |
| Time an expression | measure / measure :off |
Change self |
cd obj, cd .. |
| List all commands | help, help cmd |
| Stop in a program | binding.irb; exit, disable_irb |
| Start stepping | next, step, break, debug |
| Diagnostics | irb_info, context |
| Config | ~/.irbrc, project .irbrc, IRB.conf[...] |
| Custom commands | IRB::Command.register, IRB::HelperMethod.register |