Passing multiple blocks to a Ruby method
Something I've wanted to toy around with for a while -- here's a little pattern for passing multiple blocks to a Ruby method. This is something I find myself wishing for now and again, although at the moment I can't think of what one of those use cases were.
def generate_continue_object(*args)
args.each{|a| puts a.inspect}
yield if block_given?
continue_object = Object.new
def continue_object.next_block
if block_given?
yield
generate_continue_object
end
end
continue_object
end
generate_continue_object(1,2,3) do
puts "1/1"
end
generate_continue_object(:a, "hi") do
puts "1/3"
end.next_block do
puts "2/3"
end.next_block do
puts "3/3"
end
output:
1
2
3
1/1
:a
"hi"
1/3
2/3
3/3
I tried to do it by having generate_continue_object return a lambda and using call instead of next_block, but for some reason the lambda uses the first block only on each invocation -- I guess I'd have to somehow trick it into delaying binding, although this might be anathema to the semantics of lambda, so perhaps that's just as well.
Next steps
- allow each block to access the parameters passed
- allow each block to access values generated by the previous block?
- more generic/abstract way using this pattern in an arbitrary method definition (currently requires the "driver" method generate_continue_object)
Let me know what you think!