Java vs. Ruby: Uppercasing a string list

Here’s the vanilla Java code to uppercase a list of strings:

List words = Arrays.asList(new String[] { "Jane", "aara", "multiko" } );
List upcaseWords = new ArrayList();
for (Iterator i = words.iterator(); i.hasNext();) {
  upcaseWords.add(((String)i.next()).toUpperCase());
}

The following is Java with Apache Commons. This is probably the most functional you can get in Java, and arguably uglier than the vanilla Java above.

List words = Arrays.asList(new String[] { "Jane", "aara", "multiko" } );
List upcaseWords = CollectionUtils.collect(words, new Transformer() {
  public Object transform(Object input) {
    return ((String)input).toUpperCase();
  }
});

Here’s using Java array, rather than Array (Ruby has no such distinction):

String[] words = {"Jane", "aara", "multiko"};
List upcaseWords = new ArrayList();
for (int i = 0; i < words.length; i++) {
  upcaseWords.add(words[i].toUpperCase());
}

Below is the Ruby equivalent of the vanilla Java code. Even “verbose” Ruby is terse.

words = ['Jane', 'aara', 'multiko']
upcase_words = []
words.each { |x| upcase_words << x.upcase }

This is idiomatic Ruby:

words = %w(Jane aara multiko)
upcase_words = words.map {|x| x.upcase}

For this last one, see Understanding Ruby blocks, Procs and methods.

upcase_words = %w(Jane aara multiko).map(&:upcase)

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply