Selon newbie said:
Hi,
Please see the following code
=3D=3D=3D>8=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D
def func *args,&blk
puts *args
instance_eval &blk
end
func("a str") {puts "blk"} #OK
func "a str" do puts "blk" end #OK
func "a str" {puts "blk"} #Sytax Error!?
=3D=3D=3D>8=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D
The last call give a syntax error, which part confuse ruby?
I wonder if it has to do with precedence rules. The different block synta=
xes
have different precendence rules, with {} binding more strongly than do..=
end.
{} only binds to the last expression, while do... end binds to the whole
expression. In other words, when you write:
func "a str" do puts "blk" end
Ruby sees:
func("a str") do puts "blk" end
(you may also think of it as: '(func "a str") do puts "blk" end', which
emphasises the precedence, although I don't know if it is correct Ruby sy=
ntax)
However, when you write:
func "a str" {puts "blk"}
Ruby sees:
func("a str" {puts "blk"})
The binding is tighter, and results in a syntax error since a string can'=
t take
a block.
I don't know why the two block syntaxes have different precedence, but I =
take it
there's a reason (just like there's a reason for the existence of "and" a=
nd
""&&" with identical meanings but different precedences).
--
Christophe Grandsire.
http://rainbow.conlang.free.fr
It takes a straight mind to create a twisted conlang.