irb: the interactive shell
Start irb
irb is the interactive Ruby shell: a prompt that runs each line the moment you press Enter. Open it with one command and you will see a prompt waiting for input.
Read more about interactive mode on the Ruby basics page, then come back and type along.
Open the interactive shell
irb
irb(main):001>
Try expressions
Inside irb every line is a small program. Type an expression, press Enter, and irb prints the result right away. The comment after each line below shows what irb prints back.
2 + 2 # => 4 "hi" * 3 # => "hihihi" name = "Ada" # => "Ada" puts "Hello, #{name}" # prints Hello, Ada
Nothing is saved to a file here, so irb is perfect for quick checks. When an idea works in irb, copy it into a script file later.
Help and tab completion
irb completes code for you. Type the first letters of a word such as puts and press Tab twice: irb shows or finishes the matching names.
The launcher also documents itself. Run it with the help flag to list the available options:
List irb command line options
irb --help
Exit
When you are done experimenting, leave the shell and return to the normal terminal. Either type the exit command or press Ctrl+D on an empty line.
Leave the interactive shell
exit
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which command opens the interactive Ruby shell?
Answer
irb
irb starts the prompt; plain ruby expects a script file instead.
-
What value does irb show for the line
2 + 2?Answer
4
irb evaluates the line and shows its value, which is 4, after the => sign.
-
In the lesson block, what does the
# =>comment show?Answer
The value irb prints for that line
The comment records irb's answer, so the reader can compare.
-
What does this program print?
name = "Ada" puts "Hello, #{name}"Answer
Hello, Ada
The interpolation puts the value of name inside the string before puts prints it.
-
How do you leave irb?
Answer
Type exit or press Ctrl+D on an empty line
Both exit and Ctrl+D end the session and return to the shell.
-
Which key completes a partially typed name in irb?
Answer
Tab
Tab completes, and a second Tab lists the matching names.
-
Which command lists the options of irb itself?
Answer
irb --help
--help prints the usage of the launcher, as for most command line tools.
-
You type
name = "Ada"in irb. What does it print back?Answer
"Ada"
An assignment is an expression, and its value is the assigned string.
-
What is saved to disk when you work in irb?
Answer
Nothing, unless you copy the code into a file yourself
The session lives in memory; a working idea is copied into a script later.
-
What is true of each line typed into irb?
Answer
It is a small program, evaluated as soon as you press Enter
irb evaluates each line at once, which is why it is useful for quick checks.
Article author: Arthur Isaev