views:

208

answers:

3

I've gotten used to blocks in Ruby and would like to use them in Java. Groovy seems to offer a similar feature but I don't know enough about Groovy to understand whether there are any significant differences in syntax and functionality.

Is a Ruby block equivalent to a Groovy block?

+5  A: 

Not 100%. Ruby blocks require you to name all your parameters (as far as I know). A block in Groovy that doesn't specify parameters has one implied parameter, it.

Chris Jester-Young
Incorrect. Groovy does support named parameters to block. See: http://groovy.codehaus.org/JN2515-Closures#JN2515-Closures-ClosureParameters
jiggy
Of course Groovy supports named parameters to blocks. :-) My comment is that in Groovy, if your block takes one parameter, naming it is optional---whereas in Ruby it's mandatory.
Chris Jester-Young
Sorry, I misread :)
jiggy
+1  A: 

A block is in a sense just an anymonous function. I have never programmed java, but here are some code samples for other languages to show you that blocks are similar to passing anonymous functions.

Ruby:

def add_5
  puts yield + 5
end

add_5 { 20 }
# => 25

Javascript:

var add_5 = function(callback){
  return callback.call() + 5;
}

add_5(function(){ return 20 });
// returns 25

Lua:

local function add_5(callback)
  print(callback() + 5);
end

add_5(function()
  return 20;
end)
-- returns 25

In other words, if Java supports anonymous functions like that, you got yourself a block! As they're functions, they can take arguments, just like blocks. Here's another Lua example:

local function add_something(callback)
  callback(5 / 2);
end

add_something(function(a)
  print(a + 5);
end)
-- 7.5
August Lilleaas
A: 

I'm not 100% familiar with Ruby, but I think the answer is no. Have a look at the doc.

jiggy