Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

BasicObject#instance_exec

[U] (*untyped, **untyped) { (?) [self: self] -> U } -> U
obj.instance_exec(arg...) {|var...| block } → obj

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
See also #instance_eval #method_missing #__id__ #__send__ also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0