Ruby Language instance_eval Instance evaluation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The instance_eval method is available on all objects. It evaluates code in the context of the receiver:

object = Object.new

object.instance_eval do
  @variable = :value
end

object.instance_variable_get :@variable # => :value

instance_eval sets self to object for the duration of the code block:

object.instance_eval { self == object } # => true

The receiver is also passed to the block as its only argument:

object.instance_eval { |argument| argument == object } # => true

The instance_exec method differs in this regard: it passes its arguments to the block instead.

object.instance_exec :@variable do |name|
  instance_variable_get name # => :value
end


Got any Ruby Language Question?