Sorry, no podcast this week because I'm at the Dynamic Languages World Conference, where yesterday I managed to sit in on a Groovy Tutorial. Groovy, in case you're not aware, is "an agile and dynamic language for the Java Virtual Machine which builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk".

I'm not writing this article to portray Ruby in a negative light, I love Ruby. However, there were a few scoops of syntactic sugar which were contained in groovy which I thought were worth sharing.

Working with hashes (Maps)

Working with hashes (Maps)

1
2
3
4
5
6
def name = ["first_name":"Gregg", "last_name":"Pollack"]
println name["first_name"]
>> Gregg

name.first_name
>> Gregg

Sugar: You can automatically access the hash keys as attributes just using .
Sugar: Some people might say that using : is simpler then =>
Sugar: Think about this as respect to mock objects, instead of:

1
2
3
user = mock('User')
user.stub!(:save).and_return true 
user.stub!(:destroy).and_return false

you could have


user = ["save":true, "destroy":false]

that's hawt

Closures
1
2
3
def say_hello = { println "hello" }
say_hello()
>> "hello"

To do the same thing in Ruby:

1
2
say_hello = lambda { puts "hello" }
say_hello.call

Sugar: Kinda nice that you don't have to use lambda in Groovy.
Sugar: You also don't have to use ".call", you just use ().

1
2
[1,2,3].each { print it }
>> 123

Sugar: In a closure, if you don't specify a parameter name, "it" is used. As opposed to Ruby:

1
2
[1,2,3].each { |it| print it }
>> 123

Why do we have to specify the name of the parameter? It'd be nice to have a default like "it".

Working with arrays
1
2
["gregg", "pollack"]*.toUpperCase()
>> ["GREGG", "POLLACK"]

Sugar: They have an operator for invoking methods on each item, the equivalent in Ruby:

1
2
["Gregg", "Pollack"].collect(&:upcase)
>> ["GREGG", "POLLACK"]

Just as good, but it's kinda neat they have an operator for that.

Fetching attributes of arrays
1
2
3
4
5
6
7
name1 = ["first_name":"Gregg", "last_name":"Pollack"]
name2 = ["first_name":"Jason", "last_name":"Seifer<sp