This entry to the aforementioned CodeBrawl contest adds some extensions to facilitate the handling of multiple blocks (aka. Proc
s or lambda
s) as method arguments. It is as simple as possible while maintaining a good usability.
def method_with_multiple_blocks(*blocks)
blocks.extend ProcArray # Add basic block handling to the `blocks` array
blocks.min 1 # Require at least 2 given blocks
blocks.max 2 # Allow at most 3 given blocks
blocks.required :foo # Require a block with the given name
blocks.arities nil, 1 # Check that block #2 accepts an argument
blocks[0] # call a block by position (may be not that useful)
blocks.bar 'baz' # call a named block (with argument)
end
bar = lambda { |baz| puts baz } # Create a block and ...
bar.name = :bar # ... explicitly set its name
foo = lambda { puts 'bar' }.foo # The short syntax allows to set names that don't clash with existing methods of `Proc` (e.g. `#call`)
method_with_multiple_blocks foo, bar
# bar
# baz
Right now, there's no control over multiple Proc
s with the same names. This could be easily added, but currently the first Proc
in a ProcArray
will "win".
This is an interesting approach, but I prefer to work by name at both ends of this problem.