Syntactic Sugar in Groovy and Ruby

| Comments

Over on the RailsEnvy blog (the guys who made the “Rails vs. X commercials” last year), there’s an article that highlights some of the nice syntactic sugar that Groovy has that’s currently not available in Ruby.

I actually came to Groovy/Grails after working with Ruby/Rails for about a year. Both languages and framworks have their strengths and it’s nice to see cross-pollination of good ideas going both ways. From the comments, it sounds like Ruby 1.9 is getting some of the features that we’ve had in Groovy for a while.

One thing that I’ve missed from Ruby is the strong category support (called Mixins in Ruby). I’ve been reading that the 1.6 version of Groovy is much stronger in this area, and I’m looking forward to trying it out to see how it matches up.

I used to think that the regular expression support in Groovy was lacking compared to Ruby, but after a little digging, I found that it’s just about as easy and powerful as Ruby is.

A couple of other things that I miss from Ruby:

  • package management through RubyGems (yes, we can use maven/ivy/etc, but it’s really no where as easy as having this at your fingertips:
    sudo gem install foo
  • multiple assignment of variables on the same line (though this will be available in groovy 1.6)
    a, b = "foo", "bar"
  • block regular expressions using %r{...} - these make it much easier to document really long regular expressions rather than one huge string
  • array.first and array.last to safely retrieve the first or last element out of an array. Yes, I can use ?.getAt, but it’s not as descriptive
    def array = ["foo", "bar", "baz"]
    array?.getAt(0)   // returns "foo"
    array?.getAt(-1) // returns "baz"
  • Being able to use ||= to instantiate a variable if it doesn’t exist and set it to a default value if it doesn’t already have a value (though the Groovy “Elvis” operator gets pretty close). This example instantiates val if it doesn’t exist and gives it the default value of “start_val” and then appends “foobar”, if val does exist, it will simply append “foobar” to it.
        (val ||= ["start_val"]) << "foobar"    
  • Having the .irbrc file auto load ruby code when going into irb (the interactive ruby shell. Having a .groovyrc file that gets loaded when going into groovysh or groovyConsole would be great to attach custom enhancements to the Groovy language.

I know that some of this stuff can be added relatively easily through MOP, but it’s nice to have it right at your fingertips when you fire up a groovyConsole to try something out. The Groovy core team has been good about continuing to implement things from other languages that are useful and make sense for Groovy and overall, I’ve been a happy programmer for the last year that I’ve been using Groovy and Grails.