Back in “When Trouble Strikes” we introduced irb, a Ruby module that lets you enter Ruby programs interactively and see the results immediately. This appendix goes into more detail on using and customizing irb.
irb
is run from the command line.
irb [irb-options] [ruby_script] [options]
The command-line options for irb are listed in Table B.1. Typically, you'll run irb with no options, but if you want to run a script and watch the blow-by-blow description as it runs, you can provide the name of the Ruby script and any options for that script.
Option | Description |
---|---|
-f |
Suppress reading ~/.irbrc . |
-m |
Math mode (fraction and matrix support is available). |
-d |
Set $DEBUG to true (same as “ruby -d ”). |
-r load-module |
Same as “ruby -r ”. |
--inspect |
Use “inspect” for output (the default, unless in math mode). |
--noinspect |
Do not use inspect for output. |
--readline |
Use Readline extension module. |
--noreadline |
Do not use Readline extension module. |
--prompt prompt-mode |
Switch prompt mode. Predefined prompt modes are “default”, “simple”, “xmp”, and “inf-ruby”. |
--prompt-mode prompt-mode |
Same as --prompt . |
--inf-ruby-mode |
Sets up irb to run in inf-ruby-mode under Emacs. Changes the prompt and suppresses --readline . |
--simple-prompt |
Simple prompt mode. |
--noprompt |
Do not display a prompt. |
--tracer |
Display trace for execution of commands. |
--back-trace-limit n |
Display backtrace information using the top n and last n entries. The default value is 16. |
--irb_debug n |
Set internal debug level to n (only for irb development). |
-v, --version |
Print the version of irb. |
irb uses an initialization file in which you can set commonly used options or execute any required Ruby statements. When irb is run, it will try to load an initialization file from one of the following sources in order: ~/.irbrc
, .irbrc
, irb.rc
, _irbrc
, and $irbrc
.
Within the initialization file you may run any arbitrary Ruby code. You can also set any of the configuration values that correspond to command-line arguments as shown in Table B.2.
IRB.conf[:IRB_NAME] = "irb" |
IRB.conf[:MATH_MODE] = false |
IRB.conf[:USE_TRACER] = false |
IRB.conf[:USE_LOADER] = false |
IRB.conf[:IGNORE_SIGINT] = true |
IRB.conf[:IGNORE_EOF] = false |
IRB.conf[:INSPECT_MODE] = nil |
IRB.conf[:IRB_RC] = nil |
IRB.conf[:BACK_TRACE_LIMIT] = 16 |
IRB.conf[:USE_LOADER] = false |
IRB.conf[:USE_READLINE] = nil |
IRB.conf[:USE_TRACER] = false |
IRB.conf[:IGNORE_SIGINT] = true |
IRB.conf[:IGNORE_EOF] = false |
IRB.conf[:PROMPT_MODE] = :DEFAULT |
IRB.conf[:PROMPT] = { ... } |
IRB.conf[:DEBUG_LEVEL] = 0 |
IRB.conf[:VERBOSE] = true |
As an interesting twist on configuring irb, you can set IRB.conf[:IRB_RC]
to a Proc
object. This proc will be invoked whenever the irb context is changed, and will receive that new context as a parameter. You can use this facility to change the configuration dynamically based on the context.
At the irb prompt, you can enter any valid Ruby expression and see the results. You can also use any of the following commands to control the irb session.
exit, quit, irb_exit
cb
to change bindings (see below), exits from this binding mode.conf, irb_context
conf
.conf.back_trace_limit n
conf.debug_level = N
conf.ignore_eof = true/false
conf.ignore_sigint= true/false
conf.inf_ruby_mode = true/false
true
, changes the prompt and disables readline support, allowing irb to work with inf-ruby-mode
. (inf-ruby-mode
allows Emacs users to interact with Ruby while editing programs. See the file inf_ruby.el
in the misc
directory of the distribution for more details.) The default value is false.conf.inspect_mode = true/false/nil
true |
Display inspect (default). |
false |
Display to_s. |
nil |
Inspect mode in non-math mode, non-inspect mode in math mode. |
conf.irb_level
cb
).conf.math_mode
conf.use_loader = true/false
load
/require
.conf.prompt_c
conf.prompt_i
conf.prompt_s
conf.rc = true/false
~/.irbrc
.conf.use_prompt = true/false
conf.use_readline = true/false/nil
true |
Use Readline. |
false |
Do not use Readline. |
nil |
Use Readline except for inf-ruby-mode (default). |
conf.verbose=true/false
cb, irb_change_binding [obj]
irb [obj]
jobs, irb_jobs
fg n, irb_fg n
irb subsession number |
thread id |
irb object |
self (the obj that launched a particular subsession) |
kill n, irb_kill n
irb_fg
.You have a lot of flexibility in configuring the prompts that irb uses. Sets of prompts are stored in the prompt hash:
IRB.conf[:PROMPT]
For example, to establish a new prompt mode called “MY_PROMPT”, you might enter the following (either directly at an irb prompt or in the .irbrc
file):
IRB.conf[:PROMPT][:MY_PROMPT] = { # name of prompt mode
:PROMPT_I => "...", # normal prompt
:PROMPT_S => "...", # prompt for continuing strings
:PROMPT_C => "...", # prompt for continuing statement
:RETURN => " ==>%s\n" # format to return value
}
Then, invoke irb with the prompt mode above by
% irb --prompt my-prompt
Or set the following configuration value:
IRB.conf[:PROMPT_MODE] = :MY_PROMPT
The constants PROMPT_I
, PROMPT_S
, and PROMPT_C
specify the format for each of the prompt strings. Within the prompt format, the following flags are available and will expand to the given text:
Flag | Description |
---|---|
%N |
Current command. |
%m |
to_s of the main object (self). |
%M |
inspect of the main object (self). |
%l |
Delimiter type. In strings that are continued across a line break, %l will display the type of delimiter used to begin the string, so you'll know how to end it. The delimiter will be one of " , ' , / , ] , or ` . |
%ni |
Indent level. The optional number n is used as a width specification to printf, as printf("%nd") . |
%nn |
Current line number (n used as with the indent level). |
%% |
A literal percent sign. |
For instance, the default prompt mode is defined as follows:
IRB.conf[:PROMPT_MODE][:DEFAULT] = {
:PROMPT_I => "%N(%m):%03n:%i> ",
:PROMPT_S => "%N(%m):%03n:%i%l ",
:PROMPT_C => "%N(%m):%03n:%i* ",
:RETURN => "%s\n"
}
Because of the way irb works, there is a minor incompatibility between it and the standard Ruby interpreter. The problem lies in the determination of local variables.
Normally, Ruby looks for an assignment statement to determine if something is a variable—if a name hasn't been assigned to, then Ruby assumes that name is a method call.
eval "a = 0"
a
produces:
prog.rb:2: undefined local variable or method `a'
for #<Object:0x401c2ce0> (NameError)
In this case, the assignment is there, but it's within a string, so Ruby doesn't take it into account.
irb, on the other hand, executes statements as they are entered.
irb(main):001:0> eval "a = 0"
0
irb(main):002:0> a
0
In irb, the assignment was executed before the second line was encountered, so “a” is correctly identified as a local variable.
If you need to match the Ruby behavior more closely, you can place these statements within a begin
/end
pair.
irb(main):001:0> begin
irb(main):002:1* eval "a = 0"
irb(main):003:1> a
irb(main):004:1> end
NameError: undefined local variable or method `a'
(irb):3:in `irb_binding'
The base version of irb is installed along with Ruby itself. But there is an extended version of irb in the archives containing a few extra goodies that need mentioning.
rtags
is a command used to create a TAGS
file for use with either the emacs or vi editor.
rtags [-vi] [files]...
By default, rtags makes a TAGS
file suitable for emacs (see etags.el). The -vi
option makes a TAGS file for use with vi.
rtags needs to be installed in the same manner as irb (that is, you need to install irb in the library path and make a link from irb/rtags.rb
to bin/rtags
).
irb's xmp is an “example printer”—that is, a pretty-printer that shows the value of each expression as it is run (much like the script we wrote to format the examples in this book). There is also another stand-alone xmp in the archives.
xmp can be used as follows:
require "irb/xmp"
xmp <<END
artist = "Doc Severinsen"
artist
END
produces:
[pwd:/tc/work/ruby/ProgrammingRuby/latex]
artist = "Doc Severinsen"
==>"Doc Severinsen"
artist
==>"Doc Severinsen"
Or, it can be used as an object instance. Used in this fashion, the object maintains context between invocations:
require "irb/xmp"
x = XMP.new
x.puts <<END
artist = "Louis Prima"
END
x.puts <<END
artist
END
produces:
[pwd:/tc/work/ruby/ProgrammingRuby/latex]
artist = "Louis Prima"
==>"Louis Prima"
artist
==>"Louis Prima"
You can explicitly provide a binding with either form; otherwise, xmp uses the caller's environment.
xmp code_string, abinding
XMP.new(abinding)
Note that xmp does not work with multithreading.
The IRB::Frame
class represents the interpreter's stack and allows easy access to the Binding
environment in effect at different stack levels.
IRB::Frame.top(n = 0) |
Returns a Binding for the nth context from the top. The 0th context is topmost, most recent frame. |
IRB::Frame.bottom(n = 0) |
Returns a Binding for the nth context from the bottom. The 0th context is the bottommost, initial frame. |
IRB::Frame.sender |
Returns the object (the sender) that invoked the current method. |
You can use this facility, for instance, to examine local variables from the method that called the current method:
require 'irb/frame'
def outie
b = IRB::Frame.top(1)
eval "p my_local", b
end
def innie
my_local = 102.7
outie
end
innie
produces:
102.7
Note that this doesn't work with multithreaded programs.
Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.