user13775669
user13775669

Reputation:

Optional explicit block parameter in Ruby?

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

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

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

Upvotes: 1

Related Questions