liveBook · Manning

Instance_eval

As explained in The Well-Grounded Rubyist, Fourth Edition

instance_eval is a Ruby method that evaluates code in the context of a specified object, temporarily changing self to that object.

instance_eval runs a string or code block with the receiver of the call as self. This temporary change lets the code use that object’s context; for example, a block can access its instance variables directly. section 14.4.3

A few related behaviors clarify when to use it:

  • instance_eval accepts a string or block. Its cousin instance_exec accepts a block and passes it arguments. section 14.4.3
  • class_eval, also called module_eval, evaluates code in a class-definition context rather than shifting self to an individual receiver. section 14.4
  • Directly inspecting another object’s state can be impolite; prefer its public methods when they provide the information you need. section 14.4.3
joe = Person.new do
  name "Joe"
  age 37
end

A Person constructor can use instance_eval to run a supplied block against the new object, allowing calls such as name "Joe" and age 37 without an explicit receiver. section 14.4.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains string and block evaluation, the change to self, instance-variable access, and the argument-taking instance_exec contrast.
Examples
Uses self inspection, access to an object’s instance variable, and a Person configuration block with name and age calls.
What you can do after
Apply instance_eval to run a block in an object’s context and build a simplified object-configuration interface.
How it connects
Connects instance_eval to eval, instance_exec, class_eval, and module_eval.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.