IRB
Overview
IRB stands for “Interactive Ruby” and is a tool to interactively execute Ruby expressions read from the standard input. The irb command from your shell will start the interpreter.
IRB provides a shell-like interface that supports user interaction with the Ruby interpreter. It operates as a read-eval-print loop (REPL) that:
-
Reads each character as you type. You can modify the IRB context to change the way input works. See Input.
-
Evaluates the code each time it has read a syntactically complete passage.
-
Prints after evaluating. You can modify the IRB context to change the way output works. See Output.
Installation
Note
IRB is a default gem of Ruby, so you shouldn’t need to install it separately. However, if you’re using Ruby 2.6 or later and want to upgrade/install a specific version of IRB, follow these steps.
To install it with bundler, add this line to your application’s Gemfile:
gem 'irb'
Then execute:
$ bundle
Or install it directly with:
$ gem install irb
Usage
Note
We’re working hard to match Pry’s variety of powerful features in IRB. Track our progress or find contribution ideas in COMPARED_WITH_PRY.md.
Starting IRB
You can start a fresh IRB session by typing irb in your terminal. In the session, you can evaluate Ruby expressions or prototype small Ruby scripts. Input is executed when it is syntactically complete.
$ irb irb(main):001> 1 + 2 => 3 irb(main):002* class Foo irb(main):003* def foo irb(main):004* puts 1 irb(main):005* end irb(main):006> end => :foo irb(main):007> Foo.new.foo 1 => nil
The binding.irb Breakpoint
If you use Ruby 2.5 or later versions, you can use binding.irb in your program as breakpoints. Once binding.irb is evaluated, a new IRB session starts with the surrounding context:
$ ruby test.rb
From: test.rb @ line 2 :
1: def greet(word)
=> 2: binding.irb
3: puts "Hello #{word}"
4: end
5:
6: greet("World")
irb(main):001> word
=> "World"
irb(main):002> exit
Hello World
Debugging
You can use IRB as a debugging console with debug.gem with these options:
-
In
binding.irb, use thedebugcommand to start anirb:rdbgsession with access to alldebug.gemcommands. -
Use the
RUBY_DEBUG_IRB_CONSOLE=1environment variable to makedebug.gemuse IRB as the debugging console.
To learn more about debugging with IRB, see Debugging with IRB.
Startup
At startup, IRB:
-
Interprets (as Ruby code) the content of the configuration file (if given).
-
Constructs the initial session context from hash IRB.conf and from default values; the hash content may have been affected by command-line options, and by direct assignments in the configuration file.
-
Assigns the context to variable
conf. -
Assigns command-line arguments to variable
ARGV. -
Prints the prompt.
-
Puts the content of the