Skip to content
instance method

BasicObject#instance_eval

(::string code, ?::string filename, ?::int lineno) -> untyped
[U] () { (self) [self: self] -> U } -> U
obj.instance_eval(string [, filename [, lineno]] ) → obj
obj.instance_eval {|obj| 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 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.

Example
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
See also #__id__ #instance_exec #equal? #method_missing also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0