No grok the &block

Trying to tackle Ruby bit by bit. Got many of the basic down, but I’m
struggling to find an explanation for the significance and usefulness of
&block. I think I understand that the important part is & and “block” is
just a conventional name for the parameter, but as many times as I’ve
seen &block used in places, I just haven’t been abe to recognize what it
is doing (amid all the other reflective/dynamic stuff I’m still figuring
out).

Anyone know of a good blog post that explains what it is/how it works,
or care to tackle an explanation?

much appreciated.

– gw

Greg W. wrote:

Trying to tackle Ruby bit by bit. Got many of the basic down, but I’m
struggling to find an explanation for the significance and usefulness of
&block.

The best explanation I know is the one given by D.Black in his “Ruby for
Rails” book, section 13.3, “Callable Objects”. It takes a bit of time to
read it, but it is worth every line.

If you want a very short (and brutal) version:

  1. blocks are those { … } that float in front of a method, to which
    the method yields.
  2. when you want to access a block in a method, you need to list it in
    the arguments with an ‘&’; this lets Ruby know what this parameter
    means, but it also transforms the code block into a Proc object, that
    the method can call or pass to other methods. Eg:

def m1(&block); p block.class; block.call; end

m1 { puts “I am in a block” }

=> Proc

=> I am in a block

  1. The story is not finished; if inside the method you want to pass the
    code block to another method, you need to prepend the & again, e.g. in a
    recursion over a binary tree:

def each(&block)
@left.each(&block)
block.call(self) # same as: yield
@right.each(&block)
end

We wrote @left.each(&block); why the ‘&’ again? to retransform the Proc
into the code block that the child leaf will grab.

The essence of the story is: code blocks are NOT objects (there is no
‘Block class’), so to be called they need to be transformed into objects
(becoming a Proc); but they also need to go back to be themselves (when
we pass them to somebody that expects a code block!). The ‘&’ does the
trick during both trips!

This is a bit hard the first time you encounter it. But if you read that
section of the book, and you practice, after a few days, it becomes
second nature. Good luck

raul parolari