Reputation:
As noted in the comments, the question is actually the answer.
If the method gets a block, I want to use it further. But I also have a variant where the block isn’t needed. Can I do this in any way?
For example:
def maybe_gets_block(&blk)
if blk
STDERR.puts "Yay! I’ve got a block!"
@callback = blk
else
STDERR.puts "I don’t have a block"
@callback = nil
end
end
Upvotes: 1
Views: 860
Reputation: 84343
You're probably looking for Kernel#block_given?. Generally, you'll use that in combination with Object#yield. For example, here's a snippet that will act on an optional block or proc before falling back on some other action.
def maybe_gets_block prc=nil
if block_given?
yield
elsif prc.is_a? Proc
prc.call
else
# do something else
end
end
Upvotes: 1