Method: BasicObject#instance_eval

Defined in:
vm_eval.c

#instance_eval(string[, filename [, lineno]]) ⇒ Object #instance_eval {|| ... } ⇒ Object

Evaluates a string containing Ruby source code, or 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. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

class KlassWithSecret
  def initialize
    @secret = 99
  end
end
k = KlassWithSecret.new
k.instance_eval { @secret }   #=> 99

Overloads:

  • #instance_eval(string[, filename [, lineno]]) ⇒ Object

    Returns:

  • #instance_eval {|| ... } ⇒ Object

    Yields:

    • ()

    Returns:



# File 'vm_eval.c'

/*
 *  call-seq:
 *     obj.instance_eval(string [, filename [, lineno]] )   -> obj
 *     obj.instance_eval {| | block }                       -> obj
 *
 *  Evaluates a string containing Ruby source code, or 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. In the version of <code>instance_eval</code>
 *  that takes a +String+, the optional second and third
 *  parameters supply a filename and starting line number that are used
 *  when reporting compilation errors.
 *
 *     class KlassWithSecret
 *       def initialize
 *         @secret = 99
 *       end
 *     end
 *     k = KlassWithSecret.new
 *     k.instance_eval { @secret }   #=> 99
 */

VALUE
rb_obj_instance_eval(int argc, VALUE *argv, VALUE self)
{
    VALUE klass;

    if (SPECIAL_CONST_P(self)) {
    klass = Qnil;
    }
    else {
    klass = rb_singleton_class(self);
    }
    return specific_eval(argc, argv, klass, self);
}