Are there any significant differences between blocks in Ruby vs Groovy?

I use 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 if there are significant differences in syntax and functionality.

Is a Ruby block equivalent to a Groovy block?

+5
source share
3 answers

Not 100%. Ruby blocks require you to name all of your parameters (as far as I know). Block in Groovy, which does not indicate the parameters has one implicit parameter it.

+6
source

. java, , , .

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

, Java , ! , , . Lua:

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

add_something(function(a)
  print(a + 5);
end)
-- 7.5
+1

I am not 100% familiar with Ruby, but I think the answer is no. Take a look at the doc .

0
source

All Articles