I'm traversing an object graph and want to pass it a block that will run on each node of the structure from a method - let's called visit.
At the top, I'm going to call with a block and I want to delegate the initial call to visit on the root object to visit on other objects. I can unpack the block into a proc locally using &last_parameter_name - but how do I turn the proc back into a block on my delegated call?
Here's a simplified example where I call first(...) and want to delegate the block through to my call to second(...)
def second(&block) # ... ? ...
block.call(72)
end
def first(&block)
puts block.class # okay - now I have the Proc version
puts 'pre-doit'
block.call(42)
puts 'post-doit'
second( ... ? ...) # how do I pass the block through here?
end
first {|x| puts x*x}
Note: I need to have the same conventions on first() and second() here - i.e. they need to take the same things.
Having read and tried the answers, I've come up with a fuller, working example:
class X
def visit(&x)
x.call(50)
end
end
class Y < X
def visit(&x)
x.call(100)
X.new.visit(&x)
end
end
Y.new.visit {|x| puts x*x}
If I understand you correctly, then as simply as
second &block