[grammarians] do/end vs braces
mental@rydia.net
mental at rydia.net
Thu Dec 8 10:27:13 EST 2005
Quoting Joe Van Dyk <joevandyk at gmail.com>:
> 5.times { |i| puts i }
>
> 5.times do |i|
> puts i
> end
> Generally people save do .. end for multiline stuff. Don't think
> there's a difference in speed.
I can promise there's no speed difference. They both parse to the
same thing:
(iter
(call
(lit #<5>) times)
(dasgn_curr i)
(fcall puts
(array
(dvar i))))
(iter
(call
(lit #<5>) times)
(dasgn_curr i)
(fcall puts
(array
(dvar i))))
However, {} and do...end are not totally interchangable as syntax.
These are all equivalent:
obj.meth( 1, 2 ) { |i|
puts i
}
obj.meth( 1, 2 ) do |i|
puts i
end
obj.meth 1, 2 do |i|
puts i
end
But this will net you a parse error ('2' is not a valid method
name):
obj.meth 1, 2 { |i|
puts i
}
And these two parse equivalently:
obj.meth 1, zog { |i|
puts i
}
obj.meth( 1, zog { |i| puts i } )
Think of {} as being more "clingy" than do...end.
Basically, {} has higher precedence than do...end, just as (among
otherwise equivalent operators) && has higher precedence than
'and', and || has higher precedence than 'or'.
I'm sure Ter hates Ruby now. :)
-mental
More information about the Rubygrammar-grammarians
mailing list