简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM