End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
BasicObject#instance_exec
obj.instance_exec(arg...) {|var...| block } → obj
vm_eval.c
View on GitHub ↗
static VALUE
rb_obj_instance_exec_internal(int argc, const VALUE *argv, VALUE self)
{
VALUE klass = singleton_class_for_eval(self);
return yield_under(klass, self, argc, argv, RB_PASS_CALLED_KEYWORDS);
}
Executes the given block within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. Arguments are passed as block parameters.
Example
class KlassWithSecret def initialize @secret = 99 end end k = KlassWithSecret.new k.instance_exec(5) {|x| @secret+x } #=> 104