The Register® — Biting the hand that feeds IT

Feeds

Converting Groovy to Ruby

A different spin on Java

Customer Success Testimonial: Recovery is Everything

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.

Agentless Backup is Not a Myth

Latest Comments

Groovy v Ruby

Nice article, but what I find ironic about this article is that it does more to promote Groovy then Ruby.

What this article is saying to me is that you can almost line by line write ruby like code using groovy.

If that is the case it leaves me with the question, why would any Java developer bother to learn Ruby over Groovy.

After all you can write almost the exactly the same efficient code in Groovy that you can in Ruby, but with Groovy you gain the benefit of it's excellent integration with Java, that is far superior to JRuby.

Java programmers aren't "afraid" or incapable of learning Ruby, any competent Java programmer should be able to easily learn Ruby or almost any language like Python, etc.

What Java programmers worry about is how do you move onto more efficient languages like Ruby, while still maintaining your investment and many years of experience of Java, it's many frameworks, all the thousands of lines of legacy Java libraries you have written and integrate with all you legacy J2EE apps.

The great thing about Groovy is that you have all the benefits of Ruby's terse code, while still being able to maintain complete compatibility with all your existing Java code and libraries.

As an example I'm currently writing many classes in Groovy, compiling them and then deploying them in our legacy Spring application server. Our legacy app server doesn't know anything about Groovy and it doesn't need to know, it just sees byte code files, brilliant.

Basically Groovy allows you to access the best of both worlds.

Ruby is a great language to learn if you are new to programming, but I've yet to hear a single good reason for an experienced Java programmer to move to Ruby over Groovy? What would the benefit be?

0
0

Python

Ye, and here's the same in python:

def subn(n, list):

if not n : return [[]]

if not list : return []

remainder = list[1:]

return [it+[list[0]] for it in subn(n-1, remainder)] + subn(n, remainder)

4 lines, cleaner synthax. Ruby can suck it. :)

0
0

running intermediate steps

I have no experience of JRuby but it is worth noting that every version on the way from Java to Groovy was runnable on the JVM. This would, therefore, make a nice series of small refactorings to a codebase which has only recently embraced Groovy as well as Java

0
0

More from The Register

Bjarne Again: Hallelujah for C++
Plus: Now officially OK to admit you never used STL algorithms
Interwebs taunt Sir Jony over Apple eye candy makeover
Hey Ive, Ive... add more unicorns, willya?
SCO vs. IBM battle resumes over ownership of Unix
Zombie lawsuit back and wants to suck the brains out of Linux
Red Hat to ditch MySQL for MariaDB in RHEL 7
So long, Oracle! Don't let the door hit you on the way out
Shy? Socially inadequate? Fiddling with your phone could help
App 'tells the brutal truth' about social inadequates' chatup lines
Java EE 7 melds HTML5 with enterprise apps
New release arrives with GlassFish, NetBeans support
 breaking news
'Office Facebook' firm Tibbr wants you to PAY for mobe-meetings app
Great idea. Punters won't cough for it though
 breaking news
The only Waze is Google: Ad giant tipped to gobble map app 'for $1.3bn'
Pac-Man-satnav-ish upstart in bidding war with Apple, Facebook
 breaking news
PM Cameron calls for modern, programmable computers! (We think)
IT education musings to G8 chiefs to mystify IT industry
Apple at WWDC: Sleek new iOS, death of the big cats, pint-sized Mac Pro
CEO Cook: 'The biggest change to iOS since the introduction of the iPhone'