Changes

Jump to: navigation, search

Simple Ruby Examples

1,641 bytes added, 14:52, 12 November 2007
Executing Ruby from the Command Line
Goodbye Ruby!
</pre>
 
== Interactive Ruby Execution ==
 
In the [[What is Ruby?]] we discussed the fact that Ruby is an interpreted language. This essentially means that Ruby source code is compiled and executed at run time, rather than pre-compiled as is the case with languages such as C or C++. One of the advantages of being an interpreted language is that we can write Ruby code directly into the interpreter and have it executed in real-time. This is a great way to learn Ruby and to try out different code structures.
 
Interactive Ruby is entered using the ''irb'' tool. If you are running Windows and installed Ruby using the one click installer, you already have ''irb'' installed. If you are running on Linux, there is a good chance ''irb'' is not yet installed. Verify the installation as follows:
 
<pre>
irb -v
irb 0.9(02/07/03)
</pre>
 
If you do not get the appropriate version information displayed, you will need to install irb. On Red Hat or Fedora Linux this can be achieved as follows:
 
<pre>
su
yum install irb
</pre>
 
On Debian, Ubuntu or other Debian derived Linux distributions use the apt-get tool:
 
<pre>
sudo aptget install irb
</pre>
 
Once irb is installed, launch as follows:
 
<pre>
$ irb
irb(main):001:0>
</pre>
 
Now, we can begin to execute Ruby code:
 
<pre>
irb(main):001:0> puts 'Hello Ruby'
Hello Ruby
=> nil
irb(main):002:0>
</pre>
 
We could also perform a calculation or two:
 
<pre>
irb(main):002:0> 3 + 4
=> 7
irb(main):003:0> 8 * 7
=> 56
irb(main):004:0> 10 % 2
=> 0
</pre>
 
As you can see, anything we type at the irb prompt gets executed as soon as we press the Enter key. Ruby truly is an interactive, interpreted language.
== Executing Ruby from a File ==

Navigation menu