1

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
  • 3
    The method you have shown here should work fine. If you pass a block to `maybe_gets_block`, it will be converted to a Proc and assigned to `@callback`. If you don't pass a block, `nil` will be assigned. Is anything not working with this solution? – Holger Just Jul 08 '20 at 14:10
  • @HolgerJust Thank you! Yes, that’s right. I don’t know why I thought it wouldn’t work—I’m nearly sure I haven’t upgraded Ruby since I last tried that. Shall I delete this question then? Or keep it for other confused people? –  Jul 08 '20 at 14:15
  • @Bohdan : I would keep the question. The example is well written and the comments and the answer are enlightening. – user1934428 Jul 09 '20 at 07:01

1 Answers1

1

Using Kernel#block_given?

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
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • Doesn’t this require calling it like `maybe_gets_block(proc { puts "test" })`? –  Jul 08 '20 at 14:09
  • @Bohdan Nope. Ruby always takes an optional block. There’s no need to handle it explicitly as an argument in most cases. – Todd A. Jacobs Jul 08 '20 at 14:57