Tuesday, April 24, 2007

Ruby in 20 minutes

I was looking around the Ruby website and I found an interesting Ruby tutorial: the Ruby in Twenty Minutes. It shows cool features of that awesome programming language. It's really incredible what we can do with Ruby and with a few lines of code. For example, let's compare the Java code with Ruby code:

String[] anArray = new String[]{ "1", "2", "3", "4", "5" };
for(String elem : anArray) {
System.out.println("Number: " + elem);
}

That's a simple iteration over a String array written in Java5 or Java6. In Ruby the same thing could be written like this:

an_array = ["1", "2", "3", "4", "5"]
an_array.each {|num| puts "Number #{num}"}

That's really more simple than Java code, but it's not complex, the code between the curly braces is executed for each element in the "an_array" and the "|num|" is a reference to each element of the array. In Groovy, a Ruby-based scripting language, the code between curly braces is also known as "Closure":

an_array = ["1", "2", "3", "4", "5"]
an_array.each({ num -> println "Number ${num}" })

Closures are simple structures that can carry an implementation, it's like inner classes, but Closures are more simple and clear, see Closures for the Java Programming Language for a complete description of Closures and its adoption by Java.

1 comment:

Felipe Costa said...

Cícero,
Qualquer linguagem vai ser mais simples que Java. E você ainda nem colocou o cabeçalho todo do Java.
Eu tbm queria aprender Ruby, vai postando aí que eu vou acompanhando.

Abraço,

Felipe