irb beyond the prompt

A session with a prompt

irb is the interactive Ruby shell from lesson 3. It prints the result of every expression, which makes it the place to try one line before putting it in a file. The sessions below use --simple-prompt so the prompt is one character and the transcript is readable:

irb --simple-prompt

Switch to inspect mode.
>> 2 + 2
=> 4
>> exit

The last result is _

Every result is stored in _, so a long expression does not have to be retyped to be used in the next line. It is also the quickest way to check what a method returned without assigning it:

printf '1 + 1\n_\nexit\n' | irb --simple-prompt

Switch to inspect mode.
>> 1 + 1
=> 2
>> _
=> 2
>> exit

pp for a readable dump

The default inspect of a nested object is one long line. pp pretty-prints it with indentation, which is what you want for a hash of hashes or a JSON response:

printf 'pp({a: 1, b: [2, 3]})\nexit\n' | irb --simple-prompt

Switch to inspect mode.
>> pp({a: 1, b: [2, 3]})
{a: 1, b: [2, 3]}
=> {a: 1, b: [2, 3]}
>> exit

pp is a method from the standard library, so it works in a script too: require "pp" and call it instead of puts when a structure matters more than a sentence.

show_source

irb can show the source of a method, including methods from gems, which saves a trip to the documentation when the question is "what does this do, exactly?":

printf 'show_source greet\nexit\n' | irb --simple-prompt -r ./lib.rb

Switch to inspect mode. >> show_source greet From: /tmp/b3/lib.rb:1 def greet(name) "Hello, #{name}" end >> exit

Load a file into the session

-r requires a file before the prompt appears, so a helper you are writing is available from the first line. Change the file, run load "./lib.rb" at the prompt, and the method is redefined without leaving the session.

printf 'greet("Ada")\nexit\n' | irb --simple-prompt -r ./lib.rb

Switch to inspect mode.
>> greet("Ada")
=> "Hello, Ada"
>> exit

In a real terminal the prompt keeps a history: the up arrow recalls the last lines, and Ctrl-R searches it. The piped sessions above are only a way to put the transcript on the page.

What to watch for

irb keeps state. A variable defined ten lines ago is still there, which is convenient and also the reason a snippet that works in irb can fail in a script: the script does not have the earlier lines. When a result depends on something you typed before, put it in the file.

irb -r ./lib.rb works from the folder you start it in. A require of a gem works anywhere; a require_relative needs the file next to the one that asks for it, which is the next lesson.

Next: How a Ruby program is put together

Article author: Arthur Isaev