How to Use instance_eval in Ruby: Syntax and Examples
In Ruby,
instance_eval runs a block or string inside the context of a specific object, allowing access to its private methods and instance variables. It changes self to that object within the block, enabling dynamic code execution tied to that object.Syntax
The instance_eval method can be called on any Ruby object. It takes either a block or a string of code to execute. Inside the block, self refers to the object on which instance_eval was called.
- object.instance_eval { block }: Runs the block with
selfset toobject. - object.instance_eval(string): Evaluates the string as Ruby code in the context of
object.
ruby
object.instance_eval { block }
object.instance_eval(string)Example
This example shows how instance_eval can access and modify an object's private instance variable.
ruby
class Person def initialize(name) @name = name end private def secret "My secret name is #{@name}" end end person = Person.new("Alice") # Using instance_eval to access private method secret_message = person.instance_eval { secret } # Using instance_eval to change instance variable person.instance_eval { @name = "Bob" } new_secret_message = person.instance_eval { secret } puts secret_message puts new_secret_message
Output
My secret name is Alice
My secret name is Bob
Common Pitfalls
One common mistake is expecting instance_eval to change the class or global context; it only changes self inside the block to the receiver object. Another pitfall is using instance_eval with strings without caution, which can lead to security risks if the string comes from user input.
Also, instance_eval does not change the visibility of methods outside the block; it only allows access to private methods inside the block.
ruby
class Example def initialize @value = 10 end private def secret "Secret value is #{@value}" end end ex = Example.new # Wrong: trying to call private method directly (will raise error) # puts ex.secret # Right: use instance_eval to call private method puts ex.instance_eval { secret }
Output
Secret value is 10
Quick Reference
| Usage | Description |
|---|---|
| object.instance_eval { block } | Executes block with self as object, accessing private methods/variables. |
| object.instance_eval(string) | Evaluates string code in context of object. |
| Access private methods | Use instance_eval block to call private methods inside object. |
| Modify instance variables | Change @variables inside instance_eval block. |
| Security caution | Avoid using instance_eval with untrusted strings to prevent code injection. |
Key Takeaways
Use instance_eval to run code inside an object's context with self set to that object.
It allows access to private methods and instance variables of the object.
Avoid passing untrusted strings to instance_eval to prevent security risks.
instance_eval does not change method visibility outside its block.
Use instance_eval carefully to dynamically modify or inspect objects.
