Expand All

irb

Goals

  • Understand how and when to use irb

  • Understand how to start and stop irb

  • Understand the difference between irb and the command line

  • Execute some simple Ruby statements

Step 1

irb is the interactive ruby interpreter. It's a program that runs Ruby code as you type it in.

Start irb on the virtual machine. Any time we ask you to use irb, it should be on the Virtual Machine

Type this in the terminal:

Terminal
cd ~/Desktop/railsbridge
vagrant up
vagrant ssh
Expected result:
RailsBridge-VM:/vagrant$

Type this in the terminal:

Terminal
irb
Expected result:
irb(main): 001 >

The prompt changed. This is irb's way of reminding you that it's running, and telling you it's ready.

Hit Enter a few times.

Expected result:
irb(main): 002 >
irb(main): 003 >
irb(main): 004 >

Step 2

irb will run until you quit.

Type this in irb, hitting Enter after each line:

IRB
exit

You're back at the command line. Notice that the prompt no longer says irb.

exit is the guaranteed way to get out of irb. Depending on your operating system, Control-C or Control-D on an empty line may also work.

Practice going in and out of irb a couple of times. How can you tell when you're in irb? How can you tell when you're back at the command line?

Step 3

irb is its own program with its own commands. Although we start it from the command line, the commands to change directories and so on don't work in irb.

Restart irb.

Type this in the terminal:

Terminal
irb

Type this in irb, hitting Enter after each line:

IRB
pwd
Expected result:
NameError: undefined local variable or method `pwd' for main:Object
	from (irb):1
	from /usr/bin/irb:12:in `<main>'

This ferocious error message is irb saying "Huh? What??" because irb only understands Ruby.

Step 4

In irb, you can experiment with short pieces of code to figure out what they do.

Type this in irb, hitting Enter after each line:

IRB
5 + 9
109 / 17
2 ** 8
5 > 6

What happened after each line? What do you think these statements do?

Step 5

Lets take a closer look at the output of irb:

Type this in irb, hitting Enter after each line:

IRB
1 + 2
Expected result:
irb(main):015 > 1 + 2
 => 3
irb(main):016 >

Here, => 3 is the return value of the statement 1 + 2, the result of running your code.

Every statement in Ruby has a return value: irb shows you that value after you type a complete statement and press ENTER.

Explanation

irb is a place to experiment and find out how certain language features work. It's not a good place to write long programs. It doesn't let you save your work, and it's not a very friendly text editor.

When you write a full-fledged program, you'll save it into a text file on your computer. We'll see this in a later step.

Next Step: