# Closures syntax?

**URL:** <https://www.ruby-forum.com/t/closures-syntax/85668>\
**Category:** Ruby\
**Created:** [February 15, 2007, 12:52pm UTC](https://www.ruby-forum.com/t/closures-syntax/85668 "2007-02-15T12:52:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pedro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/919ad9/32.png) [@pedro](https://www.ruby-forum.com/u/pedro)\
**Post date:** [February 15, 2007, 12:52pm UTC](https://www.ruby-forum.com/t/closures-syntax/85668/1 "2007-02-15T12:52:54Z")

</div>

Hi, im new to ruby. I ve qaquestions about closures

1. if i defiene this

def loopN n, &b  
i=0  
while (i\<n) do  
b.call  
i+=1  
end  
end

Why the first and the second calls dosnt works and the third works?  
1.1) loopN 5, {puts “hola”} # compile error , parse error unexpected  
“{”, expected “$”  
1.2) loopN 5 {puts “hola”} # compile error , unexpected tString.  
1.2) loopN (5) {puts “hola”} # works

## thanks

* * *

Pedro Del G.

Email : removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![pedro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/919ad9/32.png) [@pedro](https://www.ruby-forum.com/u/pedro)\
**Post date:** [February 15, 2007, 1:21pm UTC](https://www.ruby-forum.com/t/closures-syntax/85668/2 "2007-02-15T13:21:56Z")

</div>

Hi,  
Am Donnerstag, 15. Feb 2007, 20:52:08 +0900 schrieb Pedro Del G.:

> Why the first and the second calls dosnt works and the third works?  
> 1.1) loopN 5, {puts “hola”} # compile error , parse error unexpected  
> “{”, expected “$”  
> 1.2) loopN 5 {puts “hola”} # compile error , unexpected tString.  
> 1.2) loopN (5) {puts “hola”} # works

Precedence. “do … end” has low precedence, applies to the leftmost  
function name, “{ …}” has high.

loopN 5 do puts “hola” end # should work

Bertram

---

<div class="post-metadata">

**Author:** ![pedro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/919ad9/32.png) [@pedro](https://www.ruby-forum.com/u/pedro)\
**Post date:** [February 15, 2007, 3:51pm UTC](https://www.ruby-forum.com/t/closures-syntax/85668/3 "2007-02-15T15:51:18Z")

</div>

On Feb 15, 2007, at 6:52 AM, Pedro Del G. wrote:

> Why the first and the second calls dosnt works and the third works?  
> 1.1) loopN 5, {puts “hola”} # compile error , parse error unexpected  
> “{”, expected “$”

Ruby doesn’t expect a comma between the last standard argument and  
the optional block argument. Drop the comma.

> 1.2) loopN 5 {puts “hola”} # compile error , unexpected tString.

The {} of the block is binding to the number 5, which is a syntax error.  
You need to add parens to clarify your intent as in:

> 1.2) loopN (5) {puts “hola”} # works

This would be more commonly written as:

loopN(5) { puts “hola”}

Alternatively you can use do/end, which has low precedence

loopN 5 do  
puts “hola”  
end

Gary W.
