I’ve been enjoying doing this for the sake of examining syntactical differences and standard API differences between Java and Ruby.

Let’s say that we have an object, call it Department. One of the methods in Department is an accessor to retrieve a department id.

Now let us say that we would like to iterate through an array of Department objects and build up a String along the way (we’ll call the String ‘out’), creating a comma-separated list of ID’s (this is a real-world problem, something that you probably have done a ton of times in one form or another).

In Java, I would probably do something like this:

  Department[] deptArray = //Create an array with departments
StringBuffer out = new StringBuffer();
//Yes, I know I could use the 'new' for loop, but I need an index
for ( int index = 0; index < deptArray.length; index++ ){
Department d = deptArray[index];
out.append( d.getId() );
if ( index != deptArray.length - 1 ){
out.append( "," );
}
}

Of course, you might write a nice utility class, that can take an arbitrary array of some type of object, and you could pass into your utility method the name of the method you wish to execute on whatever the instance type your array contains, and you could end up with a method definition something like this:

  public static String getDelimitedStringFromObjArray( 
String methodName, String delimiter, Object[] objs );

But really, that’s not the point. The point is: “How much code does it take me to do Task N using the bare bones APIs provided to me by the language.”

In Ruby:

  dept_array = //Create an array with departments
out = dept_array.collect! {|department| department.id }.join(',')

Hierarchy: previous, next