The Ruby Programming language

The Ruby Programming language

Ruby is a language of careful balance. Its creator, Yukihiro “matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.

Ruby is the interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks (as in Perl). It is simple, straight-forward, extensible, and portable.

Oh, I need to mention, it’s totally free, which means not only free of charge, but also freedom to use, copy, modify, and distribute it.

Ruby runs on many platforms, including Linux and many flavors of UNIX, MS-DOS, Windows 9x/2000/NT, BeOS, and MacOS X.

Ruby’s primary focus is productivity of program development, and users will find that programming in Ruby is productive and even fun. Ruby is well suited for the problem domains such as these:

  • Text processing—Ruby’s File, String, and Regexp classes help you process text data quickly and cleanly.
  • CGI programming—Ruby has everything you need to do CGI programming, including text-handling classes, a CGI library, database interface, and even eRuby (embedded Ruby) and mod_ruby for Apache.
  • Network programming—Network programming can be fun with Ruby’s well-designed socket classes.
  • GUI programming—GUI tool kit interfaces such as Ruby/Tk and Ruby/Gtk are available.
  • XML programming—Text-handling features and the UTF-8-aware regular expression engine make XML programming handy in Ruby. The interface to the expat XML parser library is also available.
  • Prototyping—With its high productivity, Ruby is often used to make prototypes. Prototypes sometimes become production systems by replacing the bottlenecks with C written extensions.
  • Programming education—You can teach students that programming is fun

Unlike Perl, Ruby is a genuine object-oriented language; OOP features are not an add-on. Ruby uses less punctuation ($,@,%, and so on), less context dependency, and less implicit type conversion, so Ruby programs tend to be less cryptic.

For example, the following is used in Ruby to obtain length of a string and an array:

    a = "abc"
    a.length           # => 3
    a = [1,2,3]

    a.length           # => 3

Very simple. In Perl, however, things are far more complicated:

    $a = "abc";
    length($a);        # => 3, it's OK
    @a = (1,2,3);
    length(@a);        # => 1, not as expected
    scalar(@a);        # => 3, it's the Perl way to get array size
    $a = [1,2,3];      # reference to an anonymous array
    length($a);        # => 16, not as expected

    scalar(@$a);       # => 3, need dereference to get array size

You must always be aware of data types and context in Perl, and this can be a burden for programmers. Ruby frees you of this burden.

In Ruby, most of the Perl functions are organized into class libraries. Simple Ruby programs often look like reordered and simplified Perl programs. Take a look at some examples:

-- Ruby
print "hello world"
--
-- Perl
print "hello world";
--

-- Ruby
print Time.now.strftime("%a %b %e %H:%M:%S %Y\n")
--
-- Perl
use POSIX qw(strftime);
print strftime("%a %b %e %H:%M:%S %Y\n", localtime(time()));
--

-- Ruby
require 'socket'
print TCPSocket.open("localhost", "daytime").read
--

-- Perl
use IO::Socket;

$sock = IO::Socket::INET->new(PeerAddr => 'localhost:daytime');
print <$sock>;

--

Ruby is very much influenced by Perl—in fact, some users describe Ruby as “a better Perl than Perl.”

The Ruby language is supported by a rich built-in library. This first example uses the TCPServer class to open a server socket on port 9090 and waits for incoming connections. The goal is to be able to handle HTML GET requests like http://127.0.0.1:9090/foo?bar=123.

The following Ruby code opens a server TCP socket, accepts incoming session requests, and writes each incoming request back to the user’s browser:

Listing 1
require 'socket' server = TCPServer.new('127.0.0.1', 9090) while (session = server.accept) request = session.gets puts request session.print "HTTP/1.1 200/OK\rContent-type: text/html\r\n\r\n" session.print "<html><head><title>Response from Ruby Web server</title></head>\r\n" session.print "<body>request was:" session.print request session.print "</body></html>" session.close end

The line “puts request” prints out incoming browser requests:


GET /foo?bar=123 HTTP/1.1
GET /favicon.ico HTTP/1.1

The second line printed because my browser (Safari on OS X) requested a “favorite icon” for this Web site. Fetching this response also would be simple without using a Web browser but instead using some simple Ruby TCP client code (here I use the “open-uri” library, which allows a remote resource identified by a URI to be accessed like a local file):

Listing 2
require 'open-uri' # allows the use of a file like API for URLs open("http://127.0.0.1:9090/foo?bar=123") { |file| lines = file.read puts lines }

The output would be:


<html><head><title>Response from a very simple Ruby Web server</title></head>
<body>request was:GET /foo?bar=123 HTTP/1.1
</body></html>

While extending this simple Web server to return local HTML files, etc. would be trivial, it wouldn’t make much sense: the standard Ruby library contains the flexible WEBrick Web server toolkit. If you want to set up a full-featured Web site using pure Ruby, use WEBrick! Using the standard library, you can create a full service Web server with just a few lines of code (from the WEBrick documentation):

Listing 3
require 'webrick' include WEBrick s = HTTPServer.new(:Port => 9090, :DocumentRoot => Dir::pwd + "/htdocs") trap("INT"){ s.shutdown } s.start

Sometimes writing a simple Web server from scratch in Ruby is useful. Instead of returning HTML, a simple TCP socket server can return XML data.

One-click Ruby Installer :-

A self-contained installer that includes the Ruby language, dozens of popular extensions, a syntax-highlighting editor and the book “Programming Ruby: The Pragmatic Programmer’s Guide”. Platforms: Windows NT/2000/XP, (OS X in development).

Can be found from https://rubyforge.org/projects/rubyinstaller/

You can even Try out Ruby code:

http://tryruby.hobix.com/

Give Ruby a shot right now!

Similar Posts:

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *