Hi –
On Sat, 7 Oct 2006, Huw C. wrote:
Bala P. wrote:
So this block thingy is kinda like anonymous classes?
In principle they are anonymous methods rather than classes. If you
think of them like that it should be easier to understand what’s going
on when you pass arguments into them and these arguments initialize the
block variables between the upright bars (like |cel| in the example
above).
Thinking of them as methods has some pitfalls, though, since methods
always live in modules or classes and blocks don’t.
…and Ruby replies:
parse error, unexpected ‘|’, expecting ‘}’
puts( {|cel| cel * 9 / 5 + 32}.class )
However, I may be straying into arcane areas here 
I think the best way to look at blocks is as a part of the syntax of
the Ruby method call:
[receiver dot] method_name [arg_list] [block]
Informally one does speak of blocks as anonymous functions, rather
than saying “a syntactic construct that gets wrapped in a Proc” (or
whatever). But it’s useful to keep the distinction in view that they
start life as syntax.
On that construction, a block is a kind of sibling to the argument
list – and, in both cases, they’re pure syntax: there’s no Block
class and no ArgumentList class. Also in both cases, the method can
grab what’s there and stash it in a variable:
m(a,b,c) { puts "hi" }
| | | |
def m(x,y,z,&block)
In a sense, the &block thing is really a completely separate
transaction from the x,y,z part; it might almost be represented as:
def m(x,y,z) {&block}
or something. (I’m not advocating that, just making the point that
the block and &block are going on in parallel to, rather than as part
of, the passing of arguments.)
David
–
David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org