Closures syntax ?

P

Pedro Del Gallego

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
 
B

Bertram Scharpf

Hi,
Am Donnerstag, 15. Feb 2007, 20:52:08 +0900 schrieb Pedro Del Gallego:
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
 
G

Gary Wright

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 Wright
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,234
Messages
2,571,178
Members
47,809
Latest member
Adisty

Latest Threads

Top