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.
Run irb from your shell prompt.
$ irb --simple-prompt >>
The >> 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 => to show you the return value of each line of code that you type in.
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 irb inside of Cygwin's Bash shell, run irb.bat.
By default, Cygwin's Bash shell runs inside of the Windows console, and the native Windows version of irb.bat should work fine. However, if you run a Cygwin shell inside of Cygwin's rxvt terminal emulator, then irb.bat will not run properly. You must either run your shell (and irb.bat) inside of the Windows console or install and run Cygwin's version of Ruby.
Understanding irb outputEdit
irb 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
$ irb --simple-prompt >> x=3 => 3 >> y=x*2 => 6 >> z=y/6 => 1 >> x => 3 >> exit
x=3 not only does an assignment, but also returns the value assigned to
x, which irb 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
x=3 puts x