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:
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
Post a Comment