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
1987 1988 1989 1990 1991 1992 |
# File 'vm_eval.c', line 1987 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); } |