Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

groovy

I use blocks in Ruby and would like to use them in Java. Groovy seems to offer a similar feature but I do not 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?

like image 800
Clem Aiken Avatar asked Apr 20 '09 03:04

Clem Aiken


People also ask

Is Ruby and Groovy the same?

Instacart, StackShare, and Shopify are some of the popular companies that use Ruby, whereas Groovy is used by Starbucks, PedidosYa, and Cask. Ruby has a broader approval, being mentioned in 2527 company stacks & 1114 developers stacks; compared to Groovy, which is listed in 78 company stacks and 73 developer stacks.

What is the difference between Python and Groovy?

Python is a high level, general purpose programming which supports both procedural and object-oriented programming concept. Groovy is an object-oriented programming language which is Java-syntax-compatible and Python-based the general-purpose it is used as a scripting language for java.

Is Groovy faster than Python?

Groovy can provide you with the same speed and performance which Python can deliver and vice-versa.


2 Answers

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.

like image 200
Chris Jester-Young Avatar answered Sep 28 '22 01:09

Chris Jester-Young


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
like image 37
August Lilleaas Avatar answered Sep 28 '22 02:09

August Lilleaas