Feeds

Converting Groovy to Ruby

A different spin on Java

A new approach to endpoint data protection

In this post, Glen Stampoultzis posts a very interesting and clever sequence of steps by which he converts a piece of Java code into idiomatic Groovy code. I thought it was a nice article, so I'll do a very short spin on it: taking Glen's final Groovy code and converting it into idiomatic Ruby.

(I'll probably get my pants flamed off by you-know-who, but hey, it's a slow Thursday afternoon).

Glen's code, an algorithm for finding all n-length subsequences in a given array, ends up here:

def subn(n, list) {
    if (n == 0) return [[]];
    if (list.isEmpty()) return [];

    def remainder = list.subList(1, list.size());
    return subn(n-1, remainder).collect() { [list.get(0)] + it } + subn(n, remainder);
}

(I had to make some edits because his code didn't appear to format right; I don't claim this code is 100 per cent correct in this state).

Admittedly it's a very nice reduction from the original Java code. As Glen correctly surmises, it's largely due to those super-nice closures we get from Groovy. My first step is to make a few minor changes to make it run correctly in Ruby:

def subn(n, list)
    return [[]] if (n == 0);
    return [] if (list.empty?());

    remainder = list.slice(1, list.size());
    return subn(n-1, remainder).collect() {|it| [list.at(0)] + it } + subn(n, remainder);
end

The most notable changes here are flopping the statement-modifying conditionals on the first two returns and adding an "it" parameter to the collect block. Oh, there's also the "empty?" method. But largely it looks like pretty much the same code. The next obvious step is to remove things that aren't needed in Ruby.

def subn(n, list)
    return [[]] if n == 0
    return [] if list.empty?

    remainder = list.slice(1, list.size)
    return subn(n-1, remainder).collect {|it| [list.at(0)] + it } + subn(n, remainder)
end

Mostly just removing some parens that are unnecessary (and distracting, for me) as well as line-terminating semicolons. Note that Groovy also can omit line-terminating semicolons. I think it's a matter of taste.

def subn(n, list)
    return [[]] if n == 0
    return [] if list.empty?

    remainder = list[1..-1]
    subn(n-1, remainder).collect {|it| [list[0]] + it } + subn(n, remainder)
end

Now we've eliminated the last "return" statement and made the list accesses use the array-referencing "[]" method... in the first case with a more idiomatic range of values rather than two parameters. Again, a matter of taste I suppose; two arguments works just fine. So that brings us mostly to the end of converting from the original Groovy code into Ruby. The new version is as readable as the original, but shorter by several characters. And of course this is my biased opinion, but it reads nicer too. I'm sure that will bring about all sorts of flaming in itself.

At any rate, my point in this is certainly not to start a flame war about which version is better. My point is that the Groovy and Ruby versions are still largely the same. If you can learn to produce the Groovy end result, you can just as easily learn to produce the Ruby end result. So if you've stuck with Java because you're worried you can't learn Ruby, or you don't think Ruby is enough like Java... don't be scared! A whole Rubylicious world awaits you.

Oh, and for you Rubyists out there... feel free to post your own improvements in the comments. I didn't want to change the original flow of the code, but I know it can be golfed down a lot more.

Originally published at Charles Nutter’s blog Headius. A Java developer since 1996, JRuby project-lead Charles joined Sun Microsystems in 2006.

7 Elements of Radically Simple OS Migration

More from The Register

next story
PEAK LANDFILL: Why tablet gloom is good news for Windows users
Sinofsky's hybrid strategy looks dafter than ever
Leaked Windows Phone 8.1 Update specs tease details of Nokia's next mobes
New screen sizes, dual SIMs, voice over LTE, and more
Fiendishly complex password app extension ships for iOS 8
Just slip it in, won't hurt a bit, 1Password makers urge devs
Mozilla keeps its Beard, hopes anti-gay marriage troubles are now over
Plenty on new CEO's todo list – starting with Firefox's slipping grasp
Apple: We'll unleash OS X Yosemite beta on the MASSES on 24 July
Starting today, regular fanbois will be guinea pigs, it tells Reg
Another day, another Firefox: Version 31 is upon us ALREADY
Web devs, Mozilla really wants you to like this one
Secure microkernel that uses maths to be 'bug free' goes open source
Hacker-repelling, drone-protecting code will soon be yours to tweak as you see fit
Cloudy CoreOS Linux distro declares itself production-ready
Lightweight, container-happy Linux gets first Stable release
prev story

Whitepapers

7 Elements of Radically Simple OS Migration
Avoid the typical headaches of OS migration during your next project by learning about 7 elements of radically simple OS migration.
Implementing global e-invoicing with guaranteed legal certainty
Explaining the role local tax compliance plays in successful supply chain management and e-business and how leading global brands are addressing this.
Consolidation: The Foundation for IT Business Transformation
In this whitepaper learn how effective consolidation of IT and business resources can enable multiple, meaningful business benefits.
Solving today's distributed Big Data backup challenges
Enable IT efficiency and allow a firm to access and reuse corporate information for competitive advantage, ultimately changing business outcomes.
A new approach to endpoint data protection
What is the best way to ensure comprehensive visibility, management, and control of information on both company-owned and employee-owned devices?