On 4/8/07, Chad Perrin <perrin / apotheon.com> wrote:
> On Mon, Apr 09, 2007 at 02:05:06AM +0900, andy wrote:
> > Hi,
> >
> > I am trying to learn ruby from the following site.
> >
> > http://www.rubycentral.com/book/index.html
> >
> > I am familiar with c# and java, one thing I don't understand is the
> > difference between code blocks and methods, can anyone offer a better
> > explanation than the one on the site above ?
> >
> > any help appreciated.
>
> As botp pointed out, there really isn't much of a difference between the
> two.  The major difference is how they are used.  Essentially, a block
> is a method that has no name,

Not really, blocks are instances of Proc, they are not methods:
irb(main):001:0> def block_class(&b)
irb(main):002:1>   puts b.class
irb(main):003:1>   end
=> nil
irb(main):004:0> block_class {"hello"}
Proc
=> nil
irb(main):005:0> method(:block_class).class
=> Method

Although they are close cousins, and can be substituted for each other
in many contexts.


>  is not specifically associated with any
> particular object (as far as I'm aware),

Not only are blocks associated with a particular object, self is the
receiver of the method which created the block, but also with the
local variables in the execution context of that method when the block
was created.

> and can be passed around by
> itself as an object (such as "stored in" a variable).

So can methods

irb(main):002:0> a = []
=> []
irb(main):003:0> a_get = a.method(:[])
=> #<Method: Array#[]>
irb(main):004:0> a[0] = :fred
=> :fred
irb(main):005:0> a_get.call(0)
=> :fred
irb(main):006:0>

But the pedagogical explanation that a block is an unnamed method is
useful to beginners.
-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/