Forum: Ruby Closures syntax ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F09383a4b8725aa99cf892813608de76?d=identicon&s=25 Pedro Del gallego (pedro)
on 2007-02-15 12:52
(Received via mailing list)
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 Gallego

Email              :   pedro.delgallego@gmail.com
C06869c119472a139eb163b72040b0db?d=identicon&s=25 Bertram Scharpf (Guest)
on 2007-02-15 13:21
(Received via mailing list)
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
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 Gary Wright (Guest)
on 2007-02-15 15:51
(Received via mailing list)
On Feb 15, 2007, at 6:52 AM, Pedro Del Gallego 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 Wright
This topic is locked and can not be replied to.