Method: Kernel#catch
- Defined in:
- vm_eval.c
permalink #catch([tag]) {|tag| ... } ⇒ Object
catch
executes its block. If throw
is not called, the block executes normally, and catch
returns the value of the last expression evaluated.
catch(1) { 123 } # => 123
If throw(tag2, val)
is called, Ruby searches up its stack for a catch
block whose tag
has the same object_id
as tag2. When found, the block stops executing and returns val (or nil
if no second argument was given to throw
).
catch(1) { throw(1, 456) } # => 456
catch(1) { throw(1) } # => nil
When tag
is passed as the first argument, catch
yields it as the parameter of the block.
catch(1) {|x| x + 2 } # => 3
When no tag
is given, catch
yields a new unique object (as from Object.new
) as the block parameter. This object can then be used as the argument to throw
, and will match the correct catch
block.
catch do |obj_A|
catch do |obj_B|
throw(obj_B, 123)
puts "This puts is not reached"
end
puts "This puts is displayed"
456
end
# => 456
catch do |obj_A|
catch do |obj_B|
throw(obj_A, 123)
puts "This puts is still not reached"
end
puts "Now this puts is also not reached"
456
end
# => 123
2377 2378 2379 2380 2381 2382 |
# File 'vm_eval.c', line 2377
static VALUE
rb_f_catch(int argc, VALUE *argv, VALUE self)
{
VALUE tag = rb_check_arity(argc, 0, 1) ? argv[0] : rb_obj_alloc(rb_cObject);
return rb_catch_obj(tag, catch_i, 0);
}
|