This really sucks when you need to define methods dynamically which take blocks. Sometimes you have to define the method dynamically because it needs access to variables in the current scope. If you were to use the def syntax the scope changes and those variables would no longer be accessible. For example:

We create a special “real” method which takes the block as the normal first parameter instead of as the special block parameter. Then we create a proxy method, with the name that we want to use in our code, which simply re-arranges the parameters (putting the block first) and calls the “real” method.

There’s one other possible issue. Since the method we’ll be calling from our code is still being defined with a def you might be complaining that you can’t set its name dynamically. Well there are two ways to do this. One is to just eval a string:

Sometimes though, you wan’t to use a name which has characters that the ruby parser won’t allow you to use with the def syntax. This can be accomplished with a temporary method name and a alias_method:

Yes I’m quite aware that this has been in 1.9 since the beginning. Which is why I specified Ruby 1.8 in the title of the post :)

@Drew

All your method does is basically:

def name(*a); yield *a; end

but replacing name with whatever you specify.

The point of the post is to show you how to define methods dynamically with a block. The reason you might want to use a block is to capture the variables in the current scope which you can’t do with def or with an eval.