Ruby Programming/Interactive Ruby

When learning Ruby, you will often want to experiment with new features by writing short snippets of code. Instead of writing a lot of small text files, you can use irb, which is Ruby's interactive mode.

Running irb
Run irb from your shell prompt.

$ irb --simple-prompt >>

The &gt;&gt; prompt indicates that irb is waiting for input. If you do not specify --simple-prompt, the irb prompt will be longer and include the line number. For example:

$ irb irb(main):001:0>

A simple irb session might look like this.

$ irb --simple-prompt >> 2+2 => 4 >> 5*5*5 => 125 >> exit

These examples show the user's input in bold. irb uses <tt>=&gt;</tt> to show you the return value of each line of code that you type in.

Cygwin users
If you use Cygwin's Bash shell on Microsoft Windows, but are running the native Windows version of Ruby instead of Cygwin's version of Ruby, read this section.

To run the native version of <tt>irb</tt> inside of Cygwin's Bash shell, run <tt>irb.bat</tt>.

By default, Cygwin's Bash shell runs inside of the Windows console, and the native Windows version of <tt>irb.bat</tt> should work fine. However, if you run a Cygwin shell inside of Cygwin's rxvt terminal emulator, then <tt>irb.bat</tt> will not run properly. You must either run your shell (and <tt>irb.bat</tt>) inside of the Windows console or install and run Cygwin's version of Ruby.

Understanding irb output
<tt>irb</tt> prints out the return value of each line that you enter. In contrast, an actual Ruby program only prints output when you call an output method such as.

For example:

$ irb --simple-prompt >> x=3 => 3 >> y=x*2 => 6 >> z=y/6 => 1 >> x => 3 >> exit

Helpfully,  not only does an assignment, but also returns the value assigned to , which <tt>irb</tt> then prints out. However, this equivalent Ruby program prints nothing out. The variables get set, but the values are never printed out.

x=3 y=x*2 z=y/6 x

If you want to print out the value of a variable in a Ruby program, use the  method.

x=3 puts x