Method: Kernel#block_given?

Defined in:
vm_eval.c

#block_given?Boolean

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

def try
  if block_given?
    yield
  else
    "no block"
  end
end
try                  #=> "no block"
try { "hello" }      #=> "hello"
try do "hello" end   #=> "hello"

Returns:

  • (Boolean)


2742
2743
2744
2745
2746
2747
2748
2749
2750
# File 'vm_eval.c', line 2742

static VALUE
rb_f_block_given_p(VALUE _)
{
    rb_execution_context_t *ec = GET_EC();
    rb_control_frame_t *cfp = ec->cfp;
    cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp));

    return RBOOL(cfp != NULL && VM_CF_BLOCK_HANDLER(cfp) != VM_BLOCK_HANDLER_NONE);
}