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
