Interactive Ruby Shell

优质
小牛编辑
136浏览
2023-12-01

Back on page 124 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.

Command Line


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 on page 518. 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.
irb command-line options
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
UseReadline extension module.
--noreadline
Do not useReadline extension module.
--promptprompt-mode
Switch prompt mode. Predefined prompt modes are ``default'', ``simple'', ``xmp'', and ``inf-ruby''.
--prompt-modeprompt-mode
Same as--prompt.
--inf-ruby-mode
Sets up irb to run ininf-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.

Initialization File


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 on page 518.
irb configuration values

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 setIRB.conf[:IRB_RC] to aProc 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.

Commands


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
Quits this irb session or subsession. If you've usedcb to change bindings (see below), exits from this binding mode.

conf, irb_context
Displays current configuration. Modifying the configuration is achieved by invoking methods ofconf.

conf.back_trace_limit n
Sets display lines of backtrace as top n and tail n. The default value is 16.

conf.debug_level = N
Sets debug level of irb.

conf.ignore_eof = true/false
Specifies the behavior of an end of file received on input. If true, it will be ignored; otherwise, it will quit irb.

conf.ignore_sigint= true/false
Specifies the behavior of ^C (control-c). If false, ^C will quit irb. If true, ^C during input will cancel input and return to the top level; during execution, ^C will abort the current operation.

conf.inf_ruby_mode = true/false
Iftrue, changes the prompt and disables readline support, allowing irb to work withinf-ruby-mode.[inf-ruby-mode allows Emacs users to interact with Ruby while editing programs. See the fileinf_ruby.el in themisc directory of the distribution for more details.] The default value is false.

conf.inspect_mode = true/false/nil
Specifies inspect mode according to the following values:

true
Display inspect (default).
false
Display to_s.
nil
Inspect mode in non-math mode, non-inspect mode in math mode.

conf.irb_level
Displays the current binding level (seecb).

conf.math_mode
Displays whether or not Ruby is in math mode.

conf.use_loader = true/false
Specifies whether or not irb's own file reader method is used withload/require.

conf.prompt_c
The prompt for a continuing statement (for example, immediately after an ``if'').

conf.prompt_i
The standard, top-level prompt.

conf.prompt_s
The prompt for a continuing string.

conf.rc = true/false
Specifies whether or not to use the initialization file~/.irbrc.

conf.use_prompt = true/false
Specifies whether or not to display prompts.

conf.use_readline = true/false/nil
Specifies whether or not to use Readline according to the following values:

true
Use Readline.
false
Do not use Readline.
nil
Use Readline except forinf-ruby-mode (default).

conf.verbose=true/false
Specifies whether or not verbose messages are displayed.

cb, irb_change_binding[obj]
Creates and enters a new binding that has its own scope for local variables. Ifobj is given, it will be used as self in the new binding.

irb[obj]
Starts an irb subsession. Ifobj is given, it will be used as self.

jobs, irb_jobs
Lists irb subsessions.

fg n, irb_fg n
Switches into the specified irb subsession. n may be any of the following values:

irb subsession number
thread id
irb object
self (theobj that launched a particular subsession)

kill n, irb_kill n
Kills an irb subsession. n may be any of the values as described forirb_fg.

Configuring the Prompt


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 constantsPROMPT_I,PROMPT_S, andPROMPT_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, asprintf("%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"
}

Restrictions


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 abegin/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'

rtags, xmp, and the Frame Class


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


rtags is a command used to create aTAGS file for use with either the emacs or vi editor.

rtags [
-vi
] [
files
]...

By default, rtags makes aTAGS 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 fromirb/rtags.rb tobin/rtags).

xmp


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 Frame Class


TheIRB::Frame class represents the interpreter's stack and allows easy access to theBinding environment in effect at different stack levels.

IRB::Frame.top(n = 0)
Returns aBinding for the nth context from the top. The 0th context is topmost, most recent frame.
IRB::Frame.bottom(n = 0)
Returns aBinding 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.