Using instance_eval and class_eval
No matter where you are in a Ruby program, self always has a value determined by your location in the code. Sometimes it’s useful to be able to manage that relationship and change the value of self for a while.
The methods Module#instance_eval, Module#class_eval, and Module#module_eval let you set self to be an arbitrary object, evaluate the code in a block with that object as self, and then reset self:
| "cat".instance_eval do |
| puts "Upper case = #{upcase}" |
| puts "Length is #{self.length}" |
| end |
Produces:
| Upper case = CAT |
| Length is 3 |
Inside the instance_eval block, the variable self is temporarily given the value of the object that received the instance_eval message.
All the
Get Programming Ruby 3.3 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.