Java vs. Ruby

Here are two example solutions for the problem

Write a threaded server that offers the time.

The first example is written in Java, the second in Ruby (taken from the excellent book “The Ruby Way”). Both versions are implemented to be very simple. Please judge for yourself:

Java (31 lines of code)

package at.martinus;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TimeServer {
   private static class TellTime extends Thread {
     private Socket soc;

     public TellTime(Socket soc) {
       super();
       this.soc = soc;
     }

     public void run() {
       try {
         this.soc.getOutputStream().write(new Date().toString().getBytes());
       } catch (Exception e) {
       } finally {
         try {
           this.soc.close();
         } catch (IOException e1) {
         }
       }
     }
   }

   public static void main(String args[]) throws Exception {
     ServerSocket server = new ServerSocket(12345);
     while (true) {
       new TellTime(server.accept()).start();
     }
   }

}

Starting it:

javac at/martinus/TimeServer.java
java at.martinus.TimeServer -cp .

Ruby (8 lines of codes)

require "socket"

server = TCPServer.new(12345)

while (session = server.accept)
  Thread.new(session) do |my_session|
    my_session.puts Time.new
    my_session.close
  end
end

Starting it:

ruby timeserver.rb

Taken from my comment at comp.lang.ruby.

One Response to “Java vs. Ruby”

  1. I want to see the light! « 仁力的網頁 on December 8th, 2007 10:21 am

    [...] I’ve also heard of the pay now or pay later concept. What I mean by this is Martin’s famous Java vs. Ruby timeserver example. This is a little complex so bear with me. One might look at this and say wow, Java is 4x more bloated than ruby. Or whatever. But do you see that little line “require socket” in the Ruby code? Well, I don’t think that is very fair – someone went through a lot of trouble to write a library for ruby that would allow a very short program to be written. To me it seems more fair to produce the following Java code: [...]

Leave a Reply