Method: BasicObject#instance_eval

Defined in:
vm_eval.c

#instance_eval(string[, filename [, lineno]]) ⇒ Object #instance_eval {|obj| ... } ⇒ 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 and private methods.

When instance_eval is given a block, obj is also passed in as the block’s only argument.

When instance_eval is given 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
  private
  def the_secret
    "Ssssh! The secret is #{@secret}."
  end
end
k = KlassWithSecret.new
k.instance_eval { @secret }          #=> 99
k.instance_eval { the_secret }       #=> "Ssssh! The secret is 99."
k.instance_eval {|obj| obj == self } #=> true

Overloads:

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

    Returns:

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

    Yields:

    • (obj)

    Returns:



2084
2085
2086
2087
2088
2089
# File 'vm_eval.c', line 2084

static VALUE
rb_obj_instance_eval_internal(int argc, const VALUE *argv, VALUE self)
{
    VALUE klass = singleton_class_for_eval(self);
    return specific_eval(argc, argv, klass, self, RB_PASS_CALLED_KEYWORDS);
}